ElasticSearch结合MUST和MUST_NOT

时间:2018-06-12 07:06:33

标签: elasticsearch

我需要查找所有包含列表中给定ID的文档,并且没有字段“device_data”。

我的搜索查询:

{
    "query": {
      "bool" : {
        "must" : [
          {
            "terms" : {
              "id" : [
                "1cbe0c01-6e0c-11e8-b79f-097b2a39b616"
              ]
            }
          }
        ],
        "must_not" : [
          {
            "exists" : {
              "field" : "device_data"
            }
          }
        ]
      }     
    }
}

仍然会返回此文档,我希望它不会被找到,因为“device_data”存在。我做错了什么?

{
    "took": 6,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 4.9881625,
        "hits": [
            {
                "_index": "iot_data",
                "_type": "sensors_by_id",
                "_id": "[\"1cbe0c01-6e0c-11e8-b79f-097b2a39b616\",\"1cbe0c00-6e0c-11e8-b79f-097b2a39b616\"]",
                "_score": 4.9881625,
                "_source": {
                    "field_id": "123",
                    "device_data": {
                        "comm_nr": "xxxx1",
                        "id": "542b9010-67b6-11e8-ab71-997fe8a668b8",
                        "tag": "",
                        "type": ""
                    },
                    "groups": "group-test",
                    "id": "1cbe0c01-6e0c-11e8-b79f-097b2a39b616",
                    "time": "1cbe0c00-6e0c-11e8-b79f-097b2a39b616",
                    "username": "group-test"
                }
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用终端字段,例如device_data.id

    "must_not" : [
      {
        "nested": {
          "path": "device_data",
          "query": {
            "exists" : {
              "field" : "device_data.id"
            }
          }
        }
      }
    ]