Fetch only filtered nested objects from index in elasticsearch

你说的曾经没有我的故事 提交于 2019-12-17 10:14:08

问题


I have a document with nested objects, something like this:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }, {
        "book_title": "b title 2",
        "year": 2015
    }]
}

Now I need to filter the books on by title (not book_title) and year (let's say 2014). The output I need will be:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }]
}

When I use a nested filter I get all the nested objects even if they don't match. How can I fetch only the matched nested objects?


回答1:


You need to use the nested inner_hits feature like below.

{
  "_source": [
    "title"
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "title 1"
          }
        },
        {
          "nested": {
            "path": "books",
            "query": {
              "term": {
                "books.year": 2014
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

In the output you'll get exactly what you expect, namely the title field and the matching book from the nested books array.



来源:https://stackoverflow.com/questions/32773542/fetch-only-filtered-nested-objects-from-index-in-elasticsearch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!