How to Use Range Query in Elasticsearch: Syntax and Examples
Use the
range query in Elasticsearch to filter documents where a field's value falls within a specified range. You specify the field and range boundaries using operators like gte (greater than or equal), lte (less than or equal), gt, and lt. This query works for numbers, dates, and strings.Syntax
The range query uses a JSON object where you specify the field name and the range conditions. You can use gte (greater than or equal), lte (less than or equal), gt (greater than), and lt (less than) to define the range boundaries.
Example parts explained:
field_name: The field you want to filter on.gte: Lower bound, inclusive.lte: Upper bound, inclusive.gt: Lower bound, exclusive.lt: Upper bound, exclusive.
json
{
"query": {
"range": {
"field_name": {
"gte": value1,
"lte": value2
}
}
}
}Example
This example filters documents where the price field is between 10 and 20, inclusive.
json
{
"query": {
"range": {
"price": {
"gte": 10,
"lte": 20
}
}
}
}Output
{
"hits": {
"total": 2,
"hits": [
{"_source": {"price": 10}},
{"_source": {"price": 15}}
]
}
}
Common Pitfalls
Common mistakes when using range queries include:
- Using string values without proper date format for date fields.
- Confusing inclusive (
gte,lte) and exclusive (gt,lt) operators. - Applying range queries on fields that are not mapped as numeric, date, or keyword types.
- Forgetting to use the correct field name or nested path if the field is inside nested objects.
json
{
"query": {
"range": {
"date": {
"gte": "2023-01-01",
"lte": "2023-12-31"
}
}
}
}
// Wrong: Using string without date format on a date field may cause no results.
// Correct: Ensure the field is mapped as date and the format matches the input.Quick Reference
| Operator | Meaning | Example |
|---|---|---|
| gte | Greater than or equal to | "gte": 10 |
| lte | Less than or equal to | "lte": 20 |
| gt | Greater than (exclusive) | "gt": 10 |
| lt | Less than (exclusive) | "lt": 20 |
Key Takeaways
Use the range query to filter documents by numeric, date, or string ranges.
Specify boundaries with gte, lte for inclusive and gt, lt for exclusive limits.
Ensure the field type supports range queries (numeric, date, keyword).
Match date formats correctly when filtering date fields.
Check field names and nested paths carefully to avoid empty results.