elasticsearch - ElasticSearch查询嵌套对象无法按预期工作

标签 elasticsearch elasticsearch-2.0

因此,我试图在ElasticSearch中搜索嵌套对象,但未正确执行操作,因为未得到结果。

我运行以下命令:

创建索引和映射

PUT /demo
{
    "mappings": {
        "person": {
            "properties": {
                "children": {
                    "type": "nested",
                        "properties": {
                            "fullName": {
                                "type": "string"
                            },
                            "gender": {
                                "type": "string",
                                "index": "not_analyzed"
                        }
                    }
                }
            }
        }
    }
}

添加人员文档
POST /demo/person/1
{
    "children": [{
        "fullName" : "Bob Smith",
        "gender": "M"
    }]
}

这些都按预期执行。但是,当我按照documentation中的说明搜索它们时,没有任何结果。

查询
POST /demo/person/_search
{
    "query": {
        "bool": {
            "must": [{
                "match_all": {}
            },
            {
                "nested": {
                "path": "children",
                "query": {
                    "bool": {
                        "must": [{
                            "match": {
                                "fullName": "Bob Smith"
                            }
                        }]
                    }
                }
                }
            }]
        }
    }
}

我做错了什么?

最佳答案

只是为了记录答案,问题在于所有查询和过滤器都需要完整的字段名称。在上面的示例中,文档的索引为:

{
  "children": [
    {
      "fullName" : "Bob Smith",
      "gender": "M"
    }
  ]
}

要查询gender,必须将其作为children.gender进行访问,而要查询fullName,则必须将其作为children.fullName进行查询。

Lucene有效地平整了所有JSON数据结构,这实际上就是nested类型甚至存在的全部原因,因此:
{
  "children": [
    {
      "fullName" : "Bob Smith",
      "gender": "M"
    },
    {
      "fullName" : "Jane Smith",
      "gender": "F"
    }
  ]
}

变成object类型(默认):
"children.fullName": [ "Bob Smith", "Jane Smith" ]
"children.gender": [ "M", "F" ]

使用nested类型,它变为:
{
  "children.fullName": [ "Bob Smith" ]
  "children.gender": [ "M" ]
}
{
  "children.fullName": [ "Jane Smith" ]
  "children.gender": [ "F" ]
}
{}用作嵌套文档边界(它们实际上并不存在,但从逻辑上讲它们是存在的)。

这样,无论您是否使用嵌套文档,都需要提供字段名称的完整路径,即使最后一部分(例如gender)对于索引而言是唯一的。

相关的兴趣:当数组中只有一个对象时,切勿使用nested类型。仅在将其实际用作数组时才有用。如果不是数组,则平面版本将以更少的开销提供完全相同的功能。如果某些文档只有一个,但是有些文档有多个,那么使用nested也很有意义。

关于elasticsearch - ElasticSearch查询嵌套对象无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545779/

相关文章:

java - 在Elasticsearch上删除/更新文档字段

python - 为什么elasticsearch在pypy上引发elasticsearch_dsl.exceptions.ValidationException : You cannot write to a wildcard index.而不是在cpython上?

java - Hibernate 搜索 - 删除 Elasticsearch 索引配置

elasticsearch - 限制 Elasticsearch 中每种文档类型的结果

Elasticsearch 查询跨索引搜索地理和非地理数据?

java - 默认情况下,即使在启用 Fielddata 后,文本字段上的 Fielddata 也是禁用的

ElasticSearch 6,copy_to 与动态索引映射

elasticsearch - 无法在同一台计算机上运行两个单独版本的Elasticsearch

Elasticsearch,嵌套对象的存在过滤器不起作用

elasticsearch - elasticsearch启动时如何加载索引模板文件?