How do I write a query with two search terms which matches nested objects with inner hits highlighted.
Below is the sample usecase:
I have a mapping:
"mappings": {
"properties": {
"grocery_name": {
"type": "text"
},
"items": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"stock": {
"type": "integer"
},
"category": {
"type": "text"
}
}
}
}
}
and the data looks like below
{
"grocery_name": "Elastic Eats",
"items": [
{
"name": "Red banana",
"stock": "12",
"category": "fruit"
},
{
"name": "Cavendish banana",
"stock": "10",
"category": "fruit"
},
{
"name": "peach",
"stock": "10",
"category": "fruit"
},
{
"name": "carrot",
"stock": "9",
"category": "vegetable"
},
{
"name": "broccoli",
"stock": "5",
"category": "vegetable"
}
]
}
here if i want a document which has peach and carrot both in nested docs i can do search with multiple nested queries like below
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "items",
"query": {
"match_phrase": {
"items.name": {
"query": "carrot"
}
}
}
}
},
{
"nested": {
"path": "items",
"query": {
"match_phrase": {
"items.name": {
"query": "peach"
}
}
}
}
}
]
}
}
}
the above query works perfectly, but if i add inner hits i can't add for both nested queries , if i do i get following error
[inner_hits] already contains an entry for key[items]
i want to get each matched nested object highlighted, as _source highlighting is not supported in elasticsearch is there any way i can do highlighting for each nested object?
You certainly can have multiple
inner_hits
but they need to be appropriately named:You were getting the error b/c if no name is provided, the system will default to the nested path which is
items
in both of your subqueries.