Counting the number of children when returning a parent

Extending Martijn's approch to the current Elasticsearch 1.5, we can
execute inner_hits together with has_child query, and get counts as the
score for parent documents:

{
"query": {
"has_child": {
"type": "comment",
"score_mode": "sum",
"query": {
"match_all": {}
},
"inner_hits": {}
}
}
}

Monday, 3 december 2012 г., 14:22:32 UTC+1 user Martijn v Groningen wrote:

Another trick that might be interesting to test is to use the
top_children query and then set score to sum and wrap the child
query in a constant_score query. The score of the parent would then
tell you how many child documents have matched. This trick obviously
only is useable if you don't sort by relevance, but by something else
like a field or you don't care about the ordering of the hits. The
benefit of this approach is that only one search request needs to be
executed to get the parent documents with the child count.

Martijn

On 3 December 2012 22:47, davidconde <da...@donedeal.ie <javascript:>>
wrote:

Thanks that seems to have done the job :slight_smile:

On Wednesday, 28 November 2012 18:06:38 UTC, Radu Gheorghe wrote:

Hello Dave,

It might help if you use a has_parent query[0] and do a terms facet[1]
on
the _parent field.

I've gisted an example here:
Query parents and count children · GitHub

If that works for you, you might get better performance if you replace
the
query with a facet filter[2].

The downside of this approach is that the query itself will return the
children, not the parents. That said, you can take the parent IDs from
the
facet results and get the contents using the multi get API[3].

[0]

Elasticsearch Platform — Find real-time answers at scale | Elastic

[1]

Elasticsearch Platform — Find real-time answers at scale | Elastic

[2]

Elasticsearch Platform — Find real-time answers at scale | Elastic

[3] Elasticsearch Platform — Find real-time answers at scale | Elastic

Best regards,
Radu

http://sematext.com/ -- Elasticsearch -- Solr -- Lucene

On Wed, Nov 28, 2012 at 2:48 PM, davidconde da...@donedeal.ie wrote:

I have setup a parent child relationship and I would like to be able
to
return a list of parents but also include the count of children per
parent.
Is there an easy way to do this at the moment?

Thanks,
Dave

--

--

--
Met vriendelijke groet,

Martijn van Groningen

--
You received this message because you are subscribed to the Google Groups "elasticsearch" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elasticsearch+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elasticsearch/2899e6be-64d9-4dff-9e55-e4c5dc4d3f1f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

1 Like