Scoping aggregations with query filters

112 views Asked by At

I'm using top hits aggregation in elasticsearch. However when I add a filter to the query, it returns 0 hits (expected behaviour) and the aggregations however don't match the filter and return non zero documents. I was under the impression that aggregations work in the same scope as that of the query? Does not seem to be working that way. Any ideas?

1

There are 1 answers

1
Michele Palmia On BEST ANSWER

You are probably using a top level filter instead of a filtered query. A top level filter is interpreted as a post filter and executed after the query has been executed, influencing hits but not facets.

If you simply transform your post filter into a filtered query, the aggregations will be correctly calculated on the results of your filter only.

{
   "query":{
      "filtered":{
         "filter": // your filter as before
      }
   },
   "aggs": // now they will be correctly calculated
}