Aggregation over top N hits

I want to do a terms aggregation followed by some numeric metric aggregations over top N hits. Lets say we have the following docs:

{"rank": 1, "price": 10, "name": "A"},
{"rank": 2, "price": 20, "name": "B"},
{"rank": 2, "price": 15, "name": "C"},
{"rank": 3, "price": 30, "name": "D"}

Lets say N = 2.
What I want is to take the top 2 (Here N=2) docs (when ordered by the field "rank" in ascending order) from this set and do a terms aggregation of the field "name" on those 2 docs only. This will be followed by chid aggregations: avg, sum of the field "price". I cant find any solution for this problem anywhere.

I was able to sort the docs and get top N hits using top_hits aggregation. But I was not able to do any further aggregations on those hits.

Also, I am not much familiar with painless scripts, so I dont know whether that could solve this or not. Any guide or help on this will be appreciated.

The sampler aggregation may be of use.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.