# Group By Aggregation by more than 2 fields using Java API

**URL:** <https://discuss.elastic.co/t/group-by-aggregation-by-more-than-2-fields-using-java-api/139221>\
**Category:** Elasticsearch\
**Created:** [July 9, 2018, 5:58pm UTC](https://discuss.elastic.co/t/group-by-aggregation-by-more-than-2-fields-using-java-api/139221 "2018-07-09T17:58:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pritom\_Ahmed](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/pritom_ahmed/32/20783_2.png) [@Pritom\_Ahmed](https://discuss.elastic.co/u/Pritom_Ahmed)\
**Post date:** [July 9, 2018, 5:58pm UTC](https://discuss.elastic.co/t/group-by-aggregation-by-more-than-2-fields-using-java-api/139221/1 "2018-07-09T17:58:56Z")

</div>

Hi,

I am using the JAVA API of Elasticsearch 6.3.0. I want to create a group by aggregation for more than 2 fields. Currently what I have is the following

```
        TermsAggregationBuilder termsAggregationBuilder = null;
        for (String dimension : groupBy.getDimensions()) {
            if (termsAggregationBuilder == null) {
                termsAggregationBuilder = AggregationBuilders.terms("_" + dimension).field("dimensions." + dimension + ".keyword");
            } else {
                termsAggregationBuilder.subAggregation(AggregationBuilders.terms("_" + dimension).field("dimensions." + dimension + ".keyword"));
            }
        }
        requestBuilder.addAggregation(termsAggregationBuilder);

```

The problem with this approach is that when I want to try more than 2 fields as group by, I only get results where the first fields is always present and the 2nd and 3rd fields are intermittently present (some has 2nd field, some has 3rd field)

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:** [August 6, 2018, 5:59pm UTC](https://discuss.elastic.co/t/group-by-aggregation-by-more-than-2-fields-using-java-api/139221/2 "2018-08-06T17:59:02Z")

</div>

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