# Elasticsearch terms aggregation with sub query

**URL:** <https://discuss.elastic.co/t/elasticsearch-terms-aggregation-with-sub-query/201165>\
**Category:** Elasticsearch\
**Created:** [September 26, 2019, 7:23am UTC](https://discuss.elastic.co/t/elasticsearch-terms-aggregation-with-sub-query/201165 "2019-09-26T07:23:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jayabal\_K](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jayabal_k/32/41905_2.png) [@Jayabal\_K](https://discuss.elastic.co/u/Jayabal_K)\
**Post date:** [September 26, 2019, 7:23am UTC](https://discuss.elastic.co/t/elasticsearch-terms-aggregation-with-sub-query/201165/1 "2019-09-26T07:23:04Z")

</div>

I need to aggregate the docs (term aggregation), based on the another field vale (atleast one occurrence).  
For example, I using the api traffic data, I need to get the top api list based on the total doc\_count, who has atleast one 200 ok response.

My docs has fields like apiName, responseCode,etc.

Any help on this would be appreciated?  
Thanks in advance.

---

<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:** [September 27, 2019, 3:19pm UTC](https://discuss.elastic.co/t/elasticsearch-terms-aggregation-with-sub-query/201165/2 "2019-09-27T15:19:13Z")

</div>

You can either:

1. Use your aggs but query the docs with a 200 response (this would change the API counts in your aggregations to only the status 200 hits) or
2. Do 1) to first get a list of api names and then issue a second request with a `terms` filter on the apiName field with the list of api names. The counts would have 200 and non-200 responses.

Where 2) gets challenging is if the list of api names is extremely large.

---

<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:** [October 25, 2019, 3:31pm UTC](https://discuss.elastic.co/t/elasticsearch-terms-aggregation-with-sub-query/201165/3 "2019-10-25T15:31:57Z")

</div>

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