问题
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