# Aggregation on top N results

**URL:** <https://discuss.elastic.co/t/aggregation-on-top-n-results/38679>\
**Category:** Elasticsearch\
**Created:** [January 7, 2016, 11:44pm UTC](https://discuss.elastic.co/t/aggregation-on-top-n-results/38679 "2016-01-07T23:44:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![polya](https://avatars.discourse-cdn.com/v4/letter/p/94ad74/32.png) [@polya](https://discuss.elastic.co/u/polya)\
**Post date:** [January 7, 2016, 11:44pm UTC](https://discuss.elastic.co/t/aggregation-on-top-n-results/38679/1 "2016-01-07T23:44:16Z")

</div>

This comes from [http://stackoverflow.com/questions/25429903/limiting-aggreation-to-the-top-x-hits-in-elasticsearch](http://stackoverflow.com/questions/25429903/limiting-aggreation-to-the-top-x-hits-in-elasticsearch) which I have been trying to solve as well.

question: Is there any way to build a query whose hit count has an upper limit N in order to be able to build an aggregation limited to those top N results ? And if so how ?  
Just to clarify, aggregation needs to be done on the top hits of the scope query, and not access the top hits of each bucket which (if i am right) is what the top\_hits aggregation provides. i.e. is it possible to have a sub-aggregation of the top\_hits aggregation? if so how?

---

<div class="post-metadata">

**Author:** ![softwaredoug](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/softwaredoug/32/22681_2.png) [@softwaredoug](https://discuss.elastic.co/u/softwaredoug)\
**Post date:** [January 8, 2016, 12:09am UTC](https://discuss.elastic.co/t/aggregation-on-top-n-results/38679/2 "2016-01-08T00:09:30Z")

</div>

Maybe you want the experimental sampler aggregation? I have an example  
using US high school data that uses a sampler aggregation to answer  
questions about students most similar to one under analysis. It uses a  
sampler aggregation to learn the predominant characteristics of the N most  
similar students.

> <https://github.com/o19s/student-dropout-predictor/blob/master/simStudents.py>

(If you're interested I'll be demoing this the at ElasticOn)

Doug

---

<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:** [July 5, 2017, 11:26pm UTC](https://discuss.elastic.co/t/aggregation-on-top-n-results/38679/3 "2017-07-05T23:26:15Z")

</div>


