What are range queries and how are they used in Elastic Search?
The power of Elastic Search lies in its ability to perform advanced searches through the use of range queries and aggregations. These tools allow users to perform precise searches based on specific criteria, such as numerical values or dates.
How to customize the response fields?
When a search is performed in Elastic Search, by default all the fields in the document are returned. However, it is possible to customize the search to return only the necessary information. This is done by using the "_source"
option, which allows you to specify a list of fields that we want in the response.
{ " _source": ["name", "rating"], " query": { " range": { " rating": { " gt": { " gt": 3.5, " lte": 4.5 } } } } }}
In this example, the query is configured to return only the name and rating of restaurants that meet the rating range.
How to perform range queries?
Range queries are especially useful for filtering documents with values within a certain range. Whether numbers or dates, Elastic Search allows you to define these queries easily.
-
For numbers:
When filtering by rating, the symbol GT
is used to indicate "greater than", while LTE
includes values "less than or equal to".
"range": { " rating": { " gt": 3.5, " lte": 4.5 }}
-
For dates:
When searching by last modified date, you can define the period using specific date formats.
"range": { " last_modified.date": { " gte": "2020-01-15", " lt": "2020-03-01" } }}
In these cases, the query returns documents associated with dates between January 15 and the last day of February 2020.
What are aggregations in Elastic Search?
Aggregations are powerful tools in Elastic Search that allow you to compute metrics on the data obtained in a query.
Examples of aggregations
Aggregations allow you to perform calculations such as average, maximum and minimum on search results.
{ "aggs": { "average_rating": { "avg": { "field": { "field": "rating" } } }, "max_rating": { "max": { "field": { "field": "rating" } } }, "min_rating": { "min": { "field": { "field": "rating" }} } } }
With the results, you can identify that the average, maximum and minimum rating are computed based on the returned data.
Including missing fields in aggregations
Sometimes, documents may be missing certain fields, and it is possible to define a default value for them in aggregations. This is done using the missing
property.
{ "aggs": { "average_rating": { "avg": { "field": "rating", "missing": 3.0 } } } } }} } }
Using the missing
option allows you to give a default value (in this case, 3.0) to documents that have no rating, thus affecting the calculation of the overall average.
With these tools, Elastic Search enables developers to create data filtering and aggregations in a simple and efficient way, enhancing the analysis and use of stored data. Keep learning and opening new possibilities with Elastic Search!
Want to see more contributions, questions and answers from the community?