How to aggregate a term before it's used to filter results

I have a field containing simple tags for example. I'd like to be able to use those tags to perform a faceted search but have the tag counters showing the counts of matches before the tag is used as a filter.

e.g.

Foo (20)
*Bar (25)*  <--- selected tag
Bof (23) <--- if I select this tag 'Bar' is deselected and I get 23 results (which may or may not have documents tagged `Bar`
Bif (19) 

At the moment I have a search that looks like this:

{
   "query":{
      "bool":{
         "filter":[
            {
               "term":{
                  "tag":"Bar"
               }
            }
         ]
      }
   },
   "aggs":{
      "by_tag":{
         "terms":{
            "field":"tag",
            "size":0
         }
      }
   }
}

This will give me counts for all document tags where the document is tagged Bar already

I could perform multiple searches to get the aggregations, but wondered if there was a simpler way?

Check out the post_filter expression to apply additional filters to your search results but which don't filter any aggregations.

Thanks Mark - a little more investigation has shown me the 'global' keyword and filter on aggregations. I have implemented this by copying the overall search filter and removing the one I'm interested in for each aggregation.

i couldn't see how to use post_filter aside from a simple use-case where I didn't want any filters applied to any of the aggregations, whereas I need to essentially have all my filters applied except for the filter applied on my aggregation field.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.