Quick Links
Introduction
Elasticsearch provides a wide range of query types to cater to different search requirements. Among these, the Date Range query allows users to filter documents based on the range of a date type field. This article delves into the intricacies of Elasticsearch Date Range queries, providing examples and step-by-step instructions to enhance your search operations.
Elasticsearch’s Date Range query
The Date Range query in Elasticsearch is a versatile tool that can be used to filter documents within a specific date range. It is particularly useful in scenarios where you need to retrieve documents that fall within a certain timeframe, such as logs from the last seven days, articles published within the last month, or transactions completed in the last quarter.
The basic structure of a Date Range query is as follows:
GET /_search { "query": { "range" : { "date_field" : { "gte" : "now-1d/d", "lt" : "now/d" } } } }
In this example, the `date_field` is the field in your document that contains the date. The `gte` (greater than or equal to) and `lt` (less than) parameters define the range. The value `now-1d/d` represents one day ago, and `now/d` represents the current day. This query will return all documents where the `date_field` is within the last day.
Date formats
The Date Range query supports various date formats, including but not limited to:
– Epoch milliseconds
– ISO 8601
– A combination of the above two
– Customized date formats
For instance, to search for documents from January 1, 2022, to February 1, 2022, you can use the following query:
GET /_search { "query": { "range" : { "date_field" : { "gte" : "2022-01-01", "lt" : "2022-02-01" } } } }
Time zones conversion
Elasticsearch also supports time zone conversion in Date Range queries. By default, Elasticsearch uses the UTC time zone. However, you can specify a different time zone using the `time_zone` parameter:
GET /_search { "query": { "range" : { "date_field" : { "gte" : "now-1d/d", "lt" : "now/d", "time_zone": "+01:00" } } } }
In this query, the time zone is set to “+01:00”, which corresponds to Central European Time (CET).
Date math: Time calculations simplified
Another useful feature of the Date Range query is the ability to use date math expressions. Date math allows for more complex date calculations, such as “now-1M/M” (one month ago, rounded down to the nearest month), or “now+1h” (one hour from now).
GET /_search { "query": { "range" : { "date_field" : { "gte" : "now-1M/M", "lt" : "now+1h" } } } }
Conclusion
The Date Range query offers flexible methods for specifying date constraints in your queries. You can define these constraints either with specific dates set in a given timezone or by using date math expressions. The latter allows you to specify a given point in time—either in the past or the future—without having to compute the static date expression manually.