【问题标题】:ElasticSearch querying nested objects not working as expectedElasticSearch 查询嵌套对象未按预期工作
【发布时间】:2016-07-24 07:21:04
【问题描述】:

所以我尝试在 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"
                            }
                        }]
                    }
                }
                }
            }]
        }
    }
}

我做错了什么?

【问题讨论】:

  • 你是按 fullName 处理的,但是这个字段在 Lucene 中保存为 children.fullName。只需更改为 children.fullName :)
  • @WaldemarNeto - 谢谢这是问题所在。

标签: elasticsearch elasticsearch-2.0


【解决方案1】:

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

{
  "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也是有意义的。

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2012-11-18
    • 2019-05-24
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多