How to filter an elasticsearch global aggregation?

此生再无相见时 提交于 2019-12-05 02:22:49

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"
                        }
                    }
                }
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!