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

时间:2016-07-23 19:40:20

标签: 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"
                            }
                        }]
                    }
                }
                }
            }]
        }
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

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

要查询gender,必须以children.gender进行查询并查询fullName,必须将其查询为children.fullName

所有JSON数据结构都被Lucene有效地展平,这实际上是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也是有意义的。

相关问题