# Aggregation over top N hits

**URL:** <https://discuss.elastic.co/t/aggregation-over-top-n-hits/144021>\
**Category:** Elasticsearch\
**Created:** [August 12, 2018, 7:50am UTC](https://discuss.elastic.co/t/aggregation-over-top-n-hits/144021 "2018-08-12T07:50:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sreelalkm](https://avatars.discourse-cdn.com/v4/letter/s/848f3c/32.png) [@sreelalkm](https://discuss.elastic.co/u/sreelalkm)\
**Post date:** [August 12, 2018, 7:50am UTC](https://discuss.elastic.co/t/aggregation-over-top-n-hits/144021/1 "2018-08-12T07:50:25Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [August 12, 2018, 8:22am UTC](https://discuss.elastic.co/t/aggregation-over-top-n-hits/144021/2 "2018-08-12T08:22:55Z")

</div>

The sampler aggregation may be of use.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [September 9, 2018, 8:36am UTC](https://discuss.elastic.co/t/aggregation-over-top-n-hits/144021/3 "2018-09-09T08:36:22Z")

</div>

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