# Aggregations using distinct query

**URL:** <https://discuss.elastic.co/t/aggregations-using-distinct-query/119652>\
**Category:** Elasticsearch\
**Created:** [February 13, 2018, 1:54pm UTC](https://discuss.elastic.co/t/aggregations-using-distinct-query/119652 "2018-02-13T13:54:17Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![nemi](https://avatars.discourse-cdn.com/v4/letter/n/c6cbf5/32.png) [@nemi](https://discuss.elastic.co/u/nemi)\
**Post date:** [February 13, 2018, 1:54pm UTC](https://discuss.elastic.co/t/aggregations-using-distinct-query/119652/1 "2018-02-13T13:54:17Z")

</div>

Hi, I am using ES to build term aggregations and was trying to see if there is some way of doing a "get distinct" based on a field as the first step of the aggregation. Here is what I am trying to do :

Records  
`{"my_id":"a", "someField":"X"}`  
`{"my_id":"a", "someField":"X"}`  
`{"my_id":"b", "someField":"Y"}`  
`{"my_id":"c", "someField":"Z"}`  
`{"my_id":"d", "someField":"Z"}`

And then I want to do a term aggregation by "someField" where all records having the same "my\_id" are considered only once, thus resulting in something like :  
`{ "someField": { "buckets": [{ "key": "X", "count": 1 }, { "key": "Y", "count": 1 }, { "key": "Z", "count": 2 }] } }`

**Let me underline that the bucket for X has count 1**

Any way/ideas on how to achieve this ?

Thanks!

---

<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:** [February 13, 2018, 3:12pm UTC](https://discuss.elastic.co/t/aggregations-using-distinct-query/119652/2 "2018-02-13T15:12:00Z")

</div>

Given your example I expect you want to use the `cardinality` aggregation on the `my_id` field - put this under your terms agg for `some_field`

---

<div class="post-metadata">

**Author:** ![nemi](https://avatars.discourse-cdn.com/v4/letter/n/c6cbf5/32.png) [@nemi](https://discuss.elastic.co/u/nemi)\
**Post date:** [February 27, 2018, 7:34pm UTC](https://discuss.elastic.co/t/aggregations-using-distinct-query/119652/3 "2018-02-27T19:34:18Z")

</div>

Nice, this worked great, thanks!

---

<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:** [March 27, 2018, 7:34pm UTC](https://discuss.elastic.co/t/aggregations-using-distinct-query/119652/4 "2018-03-27T19:34:21Z")

</div>

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