# Aggregate/count fields on only first X documents

**URL:** <https://discuss.elastic.co/t/aggregate-count-fields-on-only-first-x-documents/97865>\
**Category:** Elasticsearch\
**Created:** [August 22, 2017, 7:35am UTC](https://discuss.elastic.co/t/aggregate-count-fields-on-only-first-x-documents/97865 "2017-08-22T07:35:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jomarl](https://avatars.discourse-cdn.com/v4/letter/j/f08c70/32.png) [@jomarl](https://discuss.elastic.co/u/jomarl)\
**Post date:** [August 22, 2017, 7:35am UTC](https://discuss.elastic.co/t/aggregate-count-fields-on-only-first-x-documents/97865/1 "2017-08-22T07:35:19Z")

</div>

Hi,

I have a use-case were I need count the number of docs in the top X documents of my search query that have values in certain fields - taking into consideration different sort orders. E.g. "The X first documents with the given sort order contains 45 models and 70 categories".

E.g. if my search give 25000 hits, I need to be able to present how many of the 5000 first documents that has a value in the fields "modelType" and "modelCategory". Currently I'm fetching the 5000 first documents in a separate query and doing a manual count for the required fields - which is as you can imagine quite slow.

Have anyone a good solution for this case?

I have looked at the Sampler aggregation, which on paper seems to be able to solve my problem - but it is a no-go as it do not seem to consider sorting. Top-hits neither seem to solve the case.

---

<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 19, 2017, 7:35am UTC](https://discuss.elastic.co/t/aggregate-count-fields-on-only-first-x-documents/97865/2 "2017-09-19T07:35:23Z")

</div>

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