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?search_type=count
{
   "query":{
      "match": {
         "make": "ford"
      }
   },
   "aggs":{
      "recent_sales": {
         "filter": { 
            "range": {
               "sold": {
                  "from": "now-1M"
               }
            }
         },
         "aggs": {
            "average_price":{
               "avg": {
                  "field": "price" 
               }
            }
         }
      }
   }
}

Using the filter bucket to apply a filter in addition to the query scope.

This avg metric will therefore average only docs that are both ford and sold in the last month.

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.