且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何过滤弹性搜索全局聚合?

更新时间:2023-02-08 21:21:40

在我看来,这是一个 post_filter 。正如文档所述:

In my opinion this is the typical use case of a post_filter. As the doc says:


在已经计算了聚合后,post_filter应用于搜索请求最后的搜索匹配项

The post_filter is applied to the search hits at the very end of a search request, after aggregations have already been calculated

您的查询将如下所示:

{
    "post_filter":{
       "terms":{
            "family_name":"Brown" //filter_1
        }
    },
   "aggs":{
        "young_age":{
            "filter":{
                "range":{ "lt":40, "gt":18 } //filter_2
            },
            "aggs":{
                "age":{
                    "terms":{
                        "field":"age"
                    }
                }
            }
        }
    }
}

在这种情况下,搜索匹配是索引中的所有文档。然后计算聚合(在filter_1之前)。之后,将执行 post_filter 与filter_1。

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.

编辑:正如您在表达中所说的,许多聚合,只有一个不受 filter_1 的影响我使用全局聚合修复了您的查询

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"
              }
            }
          }
        }
      }
    }
  }
}