# Build relation between elasticsearch aggregators - Nested groupings

**URL:** <https://discuss.elastic.co/t/build-relation-between-elasticsearch-aggregators-nested-groupings/169525>\
**Category:** Elasticsearch\
**Created:** [February 22, 2019, 6:59am UTC](https://discuss.elastic.co/t/build-relation-between-elasticsearch-aggregators-nested-groupings/169525 "2019-02-22T06:59:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Karthikeyan\_KR](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@Karthikeyan\_KR](https://discuss.elastic.co/u/Karthikeyan_KR)\
**Post date:** [February 22, 2019, 6:59am UTC](https://discuss.elastic.co/t/build-relation-between-elasticsearch-aggregators-nested-groupings/169525/1 "2019-02-22T06:59:57Z")

</div>

Hi,

I need to create nested groupings between fields.  
Let us consider the example given below,

Documents:

> {  
> "keyword": "abc",  
> "country": "IN",  
> "state": "TN",  
> "city": "Chennai"  
> },  
> {  
> "keyword": "abc",  
> "country": "IN",  
> "state": "TN",  
> "city": "Trichy"  
> },  
> {  
> "keyword": "abc",  
> "country": "IN",  
> "state": "KL",  
> "city": "TVM"  
> },  
> {  
> "keyword": "abc",  
> "country": "US",  
> "state": "Cal",  
> "city": "California"  
> }

Required output(Something like this):

> {  
> "country": "IN",  
> "TN": [  
> "Chennai",  
> "Trichy"  
> ],  
> "KL": [  
> "TVM"  
> ]  
> },  
> {  
> "country": "US",  
> "Cal": [  
> "California"  
> ]  
> }

Query used:

> {  
> "from": 0,  
> "size": 1,  
> "aggs": {  
> "country": {  
> "terms": {  
> "field": "country.keyword",  
> "size": 50000  
> }  
> },  
> "state": {  
> "terms": {  
> "field": "state.keyword",  
> "size": 50000  
> }  
> },  
> "city": {  
> "terms": {  
> "field": "city.keyword",  
> "size": 50000  
> }  
> }  
> },  
> "query": {  
> "query\_string": {  
> "query": "(keyword:abc) "  
> }  
> }  
> }

For this query I got separate bucket as output for city , state and country.

But what I need is city should be grouped under state and state should be grouped under country.

Thanks in advance.

---

<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 22, 2019, 7:00am UTC](https://discuss.elastic.co/t/build-relation-between-elasticsearch-aggregators-nested-groupings/169525/2 "2019-03-22T07:00:05Z")

</div>

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