WARNING: The 2.x versions of Elasticsearch have passed their EOL dates. If you are running a 2.x version, we strongly advise you to upgrade.
This documentation is no longer maintained and may be removed. For the latest information, see the current Elasticsearch documentation.
Filter Bucketedit
But what if you would like to filter just the aggregation results? Imagine we are building the search page for our car dealership. We want to display search results according to what the user searches for. But we also want to enrich the page by including the average price of cars (matching the search) that were sold in the last month.
We can’t use simple scoping here, since there are two different criteria. The
search results must match ford
, but the aggregation results must match ford
AND sold > now - 1M
.
To solve this problem, we can use a special bucket called filter
. You specify
a filter, and when documents match the filter’s criteria, they are added to the
bucket.
Here is the resulting query:
GET /cars/transactions/_search { "size" : 0, "query":{ "match": { "make": "ford" } }, "aggs":{ "recent_sales": { "filter": { "range": { "sold": { "from": "now-1M" } } }, "aggs": { "average_price":{ "avg": { "field": "price" } } } } } }
Using the |
|
This |
Since the filter
bucket operates like any other bucket, you are free to nest
other buckets and metrics inside. All nested components will "inherit" the filter.
This allows you to filter selective portions of the aggregation as required.