elasticsearch 嵌套文档的弹性存在查询

nwo49xxi  于 2023-06-21  发布在  ElasticSearch
关注(0)|答案(5)|浏览(142)

我有一个嵌套的文档:

"someField": "hello",
"users": [
   {
     "name": "John",
      "surname": "Doe",
      "age": 2
   }
]

根据这个https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html,上面应该匹配:

GET /_search
{
  "query": {
    "exists" : { "field" : "users" }
  }

}
而下面的不应该,

"someField": "hello",
"users": []

但不幸的是两者并不匹配。有什么想法吗?

vaqhlq81

vaqhlq811#

Elasticsearch博客上提到的例子指的是字符串和字符串类型的数组,而不是嵌套类型。
以下查询应该对您有用:

{
    "query": {
        "nested": {
            "path": "users",
            "query": {
                "bool": {
                    "must": [
                        {
                            "exists": {
                                "field": "users"
                            }
                        }
                    ]
                }
            }
        }
    }
}

另外,您可以参考this issue以获取更多信息,其中讨论了这种使用模式。

pkbketx9

pkbketx92#

这对我很有效

GET /type/_search?pretty=true
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "outcome",
            "query": {
              "exists": {
                "field": "outcome.outcomeName"
              }
            }
          }
        }
      ]
    }
  }
}
r7knjye2

r7knjye23#

使用以下索引Map:

{
  "index_name": {
      "mappings": {
        "object_name": {
            "dynamic": "strict",
            "properties": {
              "nested_field_name": {
                  "type": "nested",
                  "properties": {
                    "some_property": {
                        "type": "keyword"
                    }
                  }
              }
            }
        }
      }
  }
}

我需要使用这个查询:

GET /index_name/_search
{
  "query": {
      "nested": {
        "path": "nested_field_name",
        "query": {
            "bool": {
              "must": [
                  {
                    "exists": {
                        "field": "nested_field_name.some_property"
                    }
                  }
              ]
            }
        }
      }
  }
}

Elasticsearch版本5.4.3

d6kp6zgx

d6kp6zgx4#

user3775217的答案对我来说很有效,但我需要调整它,使其像must_not预期的那样工作。本质上,bool/must需要 Package 在查询的nested部分:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "users",
            "query": {
              "exists": {
                "field": "users"
              }
            }
          }
        }
      ]
    }
  }
}
qoefvg9y

qoefvg9y5#

更短版本(无bool查询),(在ElasticSearch 7.x上测试)

{
  "query": {
    "nested": {
      "path": "users",
      "query": {
        "exists": {
          "field": "users"
        }
      }
    }
  }
}

相关问题