Elasticsearch:查询对象中包含的嵌套对象

时间:2016-01-07 18:05:12

标签: elasticsearch

我正在努力构建一个查询,我可以在文档的子对象上进行嵌套搜索。

说我有以下索引/映射:

curl -XPOST "http://localhost:9200/author/" -d '
{
    "mappings": {
        "item": {
            "properties": {
                "books": {
                    "type": "object",
                    "properties": {
                        "data": {
                            "type": "nested"
                        }
                    }
                }
            }
        }
    }
}
'

索引中的以下2个文件:

{
    "id": 1,
    "name": "Robert Louis Stevenson",
    "books": {
        "count": 2,
        "data": [
            {
                "id": 1,
                "label": "Treasure Island"
            },
            {
                "id": 3,
                "label": "Dr Jekyll and Mr Hyde"
            }
        ]
    }
}

{
    "id": 2,
    "name": "Philip K. Dick",
    "books": {
        "count": 1,
        "data": [
            {
                "id": 4,
                "label": "Do Android Dream of Electric Sheep"
            }
        ]
    }
}

我有一系列图书ID,比如[1,4];如何编写一个查询作者名称的关键字搜索,如果他们在数组中写了一本书,则只返回它们?

我还没有设法获得一个不会导致某种查询parse_exception的查询,但作为一个起始块,这是我查询的当前迭代 - 也许我明白哪里出错了?

{
    "query": {
        "bool": {
            "must": {
                "match": {
                    "label": "Louis"
                }
            }
        },
        "nested": {
            "path": "books.data",
            "query": {
                "bool": {
                    "must": {
                        "terms": {
                            "books.data.id": [
                                1,
                                4
                            ]
                        }
                    }
                }
            }
        }
    },
    "from": 0,
    "size": 8
}

在上述情况中,我希望返回罗伯特路易斯史蒂文森先生的文件,因为他的名字包含Louis,并且他写了书ID 1

对于它的价值,我得到的当前错误如下:

{
   "error": {
      "root_cause": [
         {
            "type": "parse_exception",
            "reason": "failed to parse search source. expected field name but got [START_OBJECT]"
         }
      ],
      "type": "search_phase_execution_exception",
      "reason": "all shards failed",
      "phase": "query",
      "grouped": true,
      "failed_shards": [
         {
            "shard": 0,
            "index": "author",
            "node": "sCk3su4YSnqhvdTGjOztlw",
            "reason": {
               "type": "parse_exception",
               "reason": "failed to parse search source. expected field name but got [START_OBJECT]"
            }
         }
      ]
   },
   "status": 400
}

这让我觉得我已经拥有了我的"嵌套"对象都错了,但文档暗示我是对的!

1 个答案:

答案 0 :(得分:2)

您几乎是正确的,%>% slice(-4) 查询必须简单地位于nested内,如下面的查询中所示。此外,bool字段需要在match字段上进行查询,因为这是存储作者姓名的位置:

name