- Learning Elastic Stack 7.0(Second Edition)
- Pranav Shukla Sharath Kumar M N
- 306字
- 2025-04-04 14:18:53
Range query on dates
A range query can also be applied to date fields since dates are also inherently ordered. You can specify the date format while querying a date range:
GET /orders/_search { "query": { "range" : { "orderDate" : { "gte": "01/09/2017", "lte": "30/09/2017", "format": "dd/MM/yyyy" } } } }
The preceding query will filter all the orders that were placed in the month of September 2017.
Elasticsearch allows us to use dates with or without the time in its queries. It also supports the use of special terms, including now to denote the current time. For example, the following query queries data from the last 7 days up until now, that is, data from exactly 24 x 7 hours ago till now with a precision of milliseconds:
GET /orders/_search { "query": { "range" : { "orderDate" : { "gte": "now-7d", "lte": "now" } } } }
The ability to use terms such as now makes this easier to comprehend.
The range query runs in filter context by default. It doesn't calculate any scores and the score is always set to 1 for all matching documents.