# Get group by and distinct count of values using other field in Elasticsearch

**URL:** <https://discuss.elastic.co/t/get-group-by-and-distinct-count-of-values-using-other-field-in-elasticsearch/278762>\
**Category:** Elasticsearch\
**Tags:** eql-elastic-query-language\
**Created:** [July 15, 2021, 10:06am UTC](https://discuss.elastic.co/t/get-group-by-and-distinct-count-of-values-using-other-field-in-elasticsearch/278762 "2021-07-15T10:06:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vinay\_Ranjan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/vinay_ranjan/32/79783_2.png) [@Vinay\_Ranjan](https://discuss.elastic.co/u/Vinay_Ranjan)\
**Post date:** [July 15, 2021, 10:06am UTC](https://discuss.elastic.co/t/get-group-by-and-distinct-count-of-values-using-other-field-in-elasticsearch/278762/1 "2021-07-15T10:06:16Z")

</div>

I have an index having document structure as below -

```auto
{
  "key": ["10", "20"],
  "keywords": [
    {
      'case': 1,
      'word': 'abc' 
    },
    {
      'case': 2,
      'word': 'def'
    },
    {
      'case': 1
      'word': abcd
    }
  ]
}

```

I need to apply filter on key=10 & get the count of distinct words by each case accros the documents. There are 20 disinct cases, so this query will return is 20 buckets at max.

**Filter Condition:** key = 10

# Result

```auto
[
    {
      'case': 1,
      'value': 2
    },
    {
      'case': 2,
      'value': 1
    }
  ]

```

Equivalent SQL Query:

```auto
select case, count(distinct words) as value 
from <table> where key = 10 and case in (1, 2, 3, 4) group by 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:** [August 12, 2021, 10:06am UTC](https://discuss.elastic.co/t/get-group-by-and-distinct-count-of-values-using-other-field-in-elasticsearch/278762/2 "2021-08-12T10:06:54Z")

</div>

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