I'm new to Elasticsearch, and come up with a question that whether Elasticsearch nested query may return only matched nested documents for nested fields or not.
For Example I have a type named blog
with a nested field named comments
{
"id": 1,
...
"comments":[
{"content":"Michael is a basketball player"},
{"content":"David is a soccer player"}
]
}
{
"id": 2,
...
"comments":[
{"content":"Wayne is a soccer player"},
{"content":"Steven is also a soccer player"},
]
}
and the nested query
{"query":{
"nested":{
"path":"comments",
"query":{"match":{"comments.content":"soccer"}}
}
}
What I need is to search blog posts with comments which mentioned "soccer", with the count of comments that matched "soccer" (in the example it counts 1, since another comment just mentioned "basketball") for each blog post.
{"hits":[
{
"id":1,
...
"count_for_comments_that_matches_query":1,
},
{
"id":2,
...
"count_for_comments_that_matches_query":2,
}
]}
However it seems Elasticsearch always return the full document, so how could I achieve it, or I couldn't?
You can search nested fields using dot notation that includes the complete path, such as obj1.name . Multi-level nesting is automatically supported, and detected, resulting in an inner nested query to automatically match the relevant nesting level, rather than root, if it exists within another nested query.
The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.
When a packed class contains an instance field that is a packed type, the data for that field is packed directly into the containing class. The field is known as a nested field .
The answer is here.
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-inner-hits.html#nested-inner-hits
You need to use the nested inner hits
feature of the Elastic search.
{
"_source": [
"id"
],
"query": {
"bool": {
"must": [
{
"match": {
"id": "1"
}
},
{
"nested": {
"path": "comments",
"query": {
"match": {
"comments.content": "soccer"
}
},
"inner_hits": {}
}
}
]
}
}
}
I think it will solve the problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With