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


(Yang Ke) #1

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?


(Camilo Sierra) #2

hello @jffifa, the only way that i know is the top hits aggregation this aggregation will return only nested hits !


(system) #3