zako
zako

Reputation: 395

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?

Upvotes: 8

Views: 3691

Answers (1)

Sarfraz Ahmad
Sarfraz Ahmad

Reputation: 1439

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

Upvotes: 1

Related Questions