In Elasticsearch, range queries allow users to find document fields that fall within specified ranges. This is very useful for scenarios where you need to filter date, time, or numeric data types. Using range queries enables efficient filtering of such data types.
Range queries are defined using the range keyword within the query. They primarily include the following parameters:
gtorgte: denote greater than and greater than or equal to, respectively.ltorlte: denote less than and less than or equal to, respectively.
Here is a specific example. Consider an e-commerce platform where Elasticsearch stores product documents, each containing a price field. If you want to query all products with prices between 50 and 150, you can use the following range query:
json{ "query": { "range": { "price": { "gte": 50, "lte": 150 } } } }
In this query:
"gte": 50indicates that the results should include products with prices greater than or equal to 50."lte": 150indicates that the results should include products with prices less than or equal to 150.
Elasticsearch processes this query and returns all matching product documents.
Additionally, range queries are not limited to numeric types; they also apply to date types. For example, if you want to query orders created within a specific date range, you can construct the query as follows:
json{ "query": { "range": { "order_date": { "gte": "2021-01-01", "lte": "2021-12-31" } } } }
In this example, the order_date field should fall within the date range specified by gte and lte.
In this way, Elasticsearch's range queries provide users with powerful data filtering capabilities, which are very suitable for scenarios requiring data filtering.