Restrict aggregation to results of filter

user2463201 picture user2463201 · Apr 2, 2014 · Viewed 21.6k times · Source

Given a set of documents that have a given value in one field, I want to know how many documents there are that have each value for a second field.

I've tried to do that with a terms aggregation with the following query:

{
    "size": 0,
    "filter": {
        "term": {
            "field1": "value"
        }
    },
    "aggregations": {
        "field2" : {
            "terms" : { "field" : "field2" }
        }
    }
}

but the returned counts show the number of documents with each value for the second field in the whole index, and not restricted to those documents with a given value for the first field.

What am I doing wrong?

Answer

Mihai Ionescu picture Mihai Ionescu · Apr 2, 2014

Have you tried using filtered query?

{
    "query": {
        "filtered": {
           "query": {
                "match_all": {}
           },
           "filter": {
               "term": {
                  "field1": "value"
               }
           }
        }
    },
    "aggregations": {
        "field2": {
           "terms": { "field": "field2" }
        }
    }
}