聚合,查询上下文和过滤器上下文在Elasticsearch 5.1中不起作用

时间:2017-04-17 10:14:56

标签: elasticsearch aggregation elasticsearch-5

我在从弹性搜索1.5迁移到5.1时遇到问题。 以下是我的弹性搜索 - 1.5查询:

{
    "_source":["_id","spotlight"],
    "query":{
        "filtered":{
            "filter":{
                "and":[
                    {"term":{"gender":"female"}},
                    {"range":{"lastlogindate":{"gte":"2016-10-19 12:39:57"}}}
                ]
            }
        }
    },
    "filter":{
        "and":[
            {"term":{"maritalstatus":"1"}}
        ]
    },
    "sort":[{"member2_dummy7":{"order":"desc"}}],
    "size":"0",
    "aggs": {

        "maritalstatus": {

            "filter": {},
            "aggs" : {

                "filtered_maritalstatus": {"terms":{"field":"maritalstatus","size":5000}}
            }
        }
    }
}

此查询在聚合中为我提供了正确的doc_count。此doc_count是在查询上下文返回的结果集上计算的,它忽略了过滤器上下文。

我在弹性搜索5.1中编写了相同的查询:

{
    "_source":["_id","spotlight"],
    "query":{
        "bool":{
            "must":[
                {"term":{"gender":"female"}},
                {"range":{"lastlogindate":{"gte":"2016-10-19 12:39:57"}}}
            ],
            "filter":{
                "bool":{
                    "must":[
                        {"term":{"maritalstatus":"1"}}
                    ]
                }
            }
        }
    },
    "sort":[{"member2_dummy7":{"order":"DESC"}}],
    "size":"0",
    "aggs": {

        "maritalstatus": {

            "filter": {},
            "aggs" : {

                "filtered_maritalstatus": {"terms":{"field":"maritalstatus","size":5000}}
            }
        }
    }

}

但是在弹性搜索5.1中,它在聚合中返回了错误的doc_count。我认为它在查询上下文中采用过滤器,因此返回错误的doc_cout。有人能告诉我在弹性搜索5.1中分离查询和过滤的正确方法吗?

1 个答案:

答案 0 :(得分:2)

您的1.5查询使用您在5.1查询中删除的post_filter

ES 5.1中的等效查询如下(filtered/filter只是被替换为bool/filter而顶层filter被重命名为post_filter):

{
  "_source": [
    "_id",
    "spotlight"
  ],
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "gender": "female"
          }
        },
        {
          "range": {
            "lastlogindate": {
              "gte": "2016-10-19 12:39:57"
            }
          }
        }
      ]
    }
  },
  "post_filter": {
    "term": {
      "maritalstatus": "1"
    }
  },
  "sort": [
    {
      "member2_dummy7": {
        "order": "desc"
      }
    }
  ],
  "size": "0",
  "aggs": {
    "maritalstatus": {
      "filter": {},
      "aggs": {
        "filtered_maritalstatus": {
          "terms": {
            "field": "maritalstatus",
            "size": 5000
          }
        }
      }
    }
  }
}