How to filter an elasticsearch global aggregation?
In my opinion this is the typical use case of a post_filter. As the doc says:
The post_filter is applied to the search hits at the very end of a search request, after aggregations have already been calculated
Your query will look like:
{ "post_filter":{ "terms":{ "family_name":"Brown" //filter_1 } }, "aggs":{ "young_age":{ "filter":{ "range":{ "lt":40, "gt":18 } //filter_2 }, "aggs":{ "age":{ "terms":{ "field":"age" } } } } }}
In this case the search hits are all the documents in the index. Then the aggregation is calculated (before filter_1). And after that the post_filter
with the filter_1 will be executed.
Edit: As you said in your commend you have many aggregations and only one that shouldn't be affected by filter_1
I fixed your query using global aggregation
{ "query": { "filtered": { "filter": { "term": { "family_name": "Brown" } } } }, "aggs": { "young_age": { "global": {}, "aggs": { "filter2": { "filter": { "range": { "lt": 40, "gt": 18 } }, "aggs": { "age": { "terms": { "field": "age" } } } } } } }}
globals and filters are not allowed at same level. you have to put filter at one level inside to global aggregation.
something like this should do for you.
{ "query":{ "filtered":{ "filter":{ "terms":{ "family_name":"Brown" } } } }, "aggs":{ "young_age":{ "global":{}, "aggs":{ "filter": {"term": {"family_name": "Brown"}}, #or {"bool": {"filter": {"term": {"family_name": "Brown"}}}} "aggs": { "age":{ "terms":{ "field":"age" } } } } } }}