首页 > 解决方案 > Elasticsearch 应该使用 must_not - 非嵌套

问题描述

刚接触 Elasticsearch,正在研究一个我不愿更改的遗留模型。我有日期字段,如果它的值是我们不会输入的null(我认为是因为 ES 处理的方式0000-00-00)。我希望能够查询具有特定日期或字段不存在的数据。这是我所拥有的:

{
    "size": 10000,
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "AccountID": "xxxx"
                    }
                },
                {
                    "term": {
                        "LocationID": "xxxx"
                    }
                },
                {
                    "should": [
                        {
                            "range": {
                                "CloseDate": {
                                    "gte": "2020-11-01",
                                    "lte": "2020-12-02"
                                }
                            }
                        },
                        {
                            "bool": {
                                "must_not": {
                                    "exists": {
                                        "field": "CloseDate"
                                    }
                                }
                            }
                        }
                    ]
                }
            ]
        }
    }
}

[should] query malformed, no start_object after query name我在尝试这个时得到了错误。是否有替代语法或确实格式错误?

标签: elasticsearchaws-elasticsearch

解决方案


一个must子句中可以有多个查询[]。请注意,这should也是查询的子句,bool而不是查询本身。因此它应该在里面bool

{
  "size": 10000,
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "AccountID": "xxxx"
          }
        },
        {
          "term": {
            "LocationID": "xxxx"
          }
        },
        {
          "bool": {            <------------- Note this
            "should": [
              {
                "range": {
                  "CloseDate": {
                    "gte": "2020-11-01",
                    "lte": "2020-12-02"
                  }
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "CloseDate"
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

推荐阅读