Question

I'm struggling writing an ElasticSearch query with facet counts. The query itself needs two conditions:

  1. a condition which restricts the document set, excluded documents should not be used for the facet count.
  2. a condition which restricts the result set but excluded documents should be part of the facet count.

Example documents:

{"user": "editor", "tag": "foo"}
{"user": "editor", "tag": "bar"}

query:

{
    "query" : { 
        "constant_score": {
            "filter": {"term": {"user": "editor"} }
        }
    },
    "facets" : {
        "tag" : { "terms" : {"field" : "tag"} }
    }
}

The result of this query is ok, I see a facet count for tag foo+bar correctly. Now I'd like to extend the query so the results only display documents with tag "foo" BUT keep the facet count as before (so tag "bar" should also appear in the facet count).

For example if I modify the constant_score filter like this:

"filter": {
    "and": [{"term": {"user": "editor"}}, {"term": {"tag": "foo"}}]
}

then obviously only the tag "foo" will appear in the facet count so I need to add the {"term": {"tag": "foo"}} filter somewhere else.

How do I do that in ElasticSearch?

Was it helpful?

Solution

Based on what ES documentation says:

While search queries restrict both the returned documents and facet counts, search filters restrict only returned documents — but not facet counts.

Something like that might work:

{
    "query" : { 
        "constant_score": {
            "filter": {"term": {"user": "editor"} }
        }
    },
    "filter" : {"term": {"tag": "foo"} },
    "facets" : {
        "tag" : { "terms" : {"field" : "tag"} }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top