Throughout this guide, you will learn to define a range parameter in your search query using Boolean expressions such as greater than, less than, and more.
Elasticsearch Range Query: Basic Usage
To specify a specific range in a search query, we can use the range parameter followed by the field and the conditions to check.
Take the query below that returns the documents where the field AvgTicketPrice is greater than 600 and less than 800
{
"query": {
"range": {
"AvgTicketPrice": {
"gte": 600,
"lte": 800
}
}
}
}
Below is the example return results:
Understanding the Query
In the example above, we set the range in the query. The range keyword requires the field parameter, which defines the field to search.
We then proceed to define the parameter for the field. These are Boolean conditions such as:
- gt – greater than
- gte – greater than or equal to
- lt – less than
- lte – less than or equal to
Querying a Time Range
If the field you wish to search is of type date, you can use the above conditionals followed by the date math defined in the resource below:
Consider the following value that uses the time_zone parameter to convert the time to UTC value and searches for a range.
{
"query": {
"range": {
"timestamp": {
"time_zone": "+03:00",
"gte": "2021-10-14T05:22:14",
"lte": "now"
}
}
}
}
The above query should return the documents where the timestamp is greater than 2021-10-14 at 05:22:14.
Here are example results:
NOTE: time_zone does not affect the now parameter.
Greater than
You do not have to combine the conditionals such as greater than and less than; you can use an individual range, as shown in the example below:
{
"query": {
"range": {
"DistanceMiles": {
"gte": 10000
}
}
}
}
The example above returns the documents where the DistanceMiles is greater than 10000.
The response is below:
Boolean
To check for a range where the field type is a Boolean value, you can use lte or gte. For example, to get the documents for canceled flights, we can run a request as:
{
"query": {
"range": {
"Cancelled": {
"gte": true
}
}
}
}
In the example above, we pass the range to check as a Boolean true.
The results are as shown:
Closing
In this guide, you learned how to use the range query in Elasticsearch to filter for results that match a specific range.