弹性存在查询嵌套文档

时间:2017-01-05 18:18:54

标签: elasticsearch

我有一个嵌套文档:

"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": []

但不幸的是两者都不匹配。任何想法?

3 个答案:

答案 0 :(得分:28)

Elasticsearch博客中提到的示例引用字符串和字符串类型数组,而不是嵌套类型。

以下查询适合您:

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

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

答案 1 :(得分:4)

使用以下索引映射:

{
  "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

答案 2 :(得分:2)

这对我有用

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