Search code examples
elasticsearchfilterfacet

ElasticSearch: getting facets from all results with filter query


I don't know whether the title of this question is clear enough.

I have a text search with language filter in the left pane in ElasticSearch. When a specific language filter is selected in the left pane from search results (from a query), I still want to get the language facets from all search results from the query. I know this is possible in Solr but I am not sure whether this is doable in ElasticSearch.


Solution

  • Yes, you can achieve this by using post_filter instead of a normal filter. What post_filter does is to filter the documents after the aggregations have been computed on the full data set.

    So instead of this:

    {
      "query": {
        "bool": {
          "filter": {
            "term": {
              "some_field": "some_value"
            }
          }
        }
      },
      "aggs": {
        "languages": {
          "terms": {
            "field": "language"
          }
        }
      }
    }
    

    Do this:

    {
      "post_filter": {
        "term": {
          "some_field": "some_value"
        }
      },
      "aggs": {
        "languages": {
          "terms": {
            "field": "language"
          }
        }
      }
    }