Nested queries in Elastic search which should apply on all objects in nested array

时间:2017-08-04 12:51:48

标签: elasticsearch elasticsearch-dsl

Hi I have this document in ES with nested type:

{
         "id": "92210f7f-b8a4-4d55-877d-8708154aa004",
          "additionalData": {

              "devices_nested": [
                {
                  "version_string": "1"
                },
                {
                  "os_string": "Windows",
                  "version_string": "3"
                },
                {
                  "os_string": "Centos"
                }
              ]

          }

I want to do query that additionalData.devices_nested does not contain any element where os_string property does not exist that means I want to avoid such documents where some entries could have or not os_string property. Here is my query:

{
  "query": {
    "nested": {
      "query": {
        "bool": {
          "must": {
            "exists": {
              "field": "additionalData.devices_nested.os_string"
            }
          }
        }
      },
      "path": "additionalData.devices_nested"
    }
  }
}

But I always get the example document as result because at least one element satisfies query that there is os_string property. Is it possible to make query which will return document where all elements in devices_nested has os_string property?

1 个答案:

答案 0 :(得分:0)

  

是否可以进行返回文档的查询,其中devices_nested中的所有元素都具有os_string属性?

是的,它是可行的。您必须使用 must_not missing 方法,而不是必须存在

在以下查询中,nested内的bool条件将匹配至少一个嵌套对象中没有os_string字段的所有文档,然后是外部must_not查询将排除这些文件。因此,您只能获得所有嵌套对象中包含os_string字段的文档:

{
  "query": {
    "bool": {
        "must_not": {
            "nested": {
              "query": {
                "bool": {
                    "must_not": {
                        "exists": {
                            "field": "additionalData.devices_nested.os_string"
                        }
                    }
                }
              },
              "path": "additionalData.devices_nested"
            }
        }
    }
  }
}