8

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.