Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May Elasticsearch nested query return only matched nested documents for nested fields?

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?

like image 587
zako Avatar asked May 19 '15 10:05

zako


People also ask

How do I search in nested fields?

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.

What is nested type in Elasticsearch?

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.

What is a nested field?

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 .


1 Answers

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

like image 151
Sarfraz Ahmad Avatar answered Oct 06 '22 06:10

Sarfraz Ahmad