# Sub Aggregation in new JAVA Api Client

**URL:** <https://discuss.elastic.co/t/sub-aggregation-in-new-java-api-client/313447>\
**Category:** Elasticsearch\
**Tags:** language-clients\
**Created:** [September 1, 2022, 1:16pm UTC](https://discuss.elastic.co/t/sub-aggregation-in-new-java-api-client/313447 "2022-09-01T13:16:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sarthak\_Agarwal](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/sarthak_agarwal/32/110339_2.png) [@Sarthak\_Agarwal](https://discuss.elastic.co/u/Sarthak_Agarwal)\
**Post date:** [September 1, 2022, 1:16pm UTC](https://discuss.elastic.co/t/sub-aggregation-in-new-java-api-client/313447/1 "2022-09-01T13:16:06Z")

</div>

```auto
TermsAggregationBuilder term = AggregationBuilders.terms("agg1").field("test");
term.size(100);

FilterAggregationBuilder filterAgg = new FilterAggregationBuilder("agg2", new MatchAllQueryBuilder()).subAggregation(term);

```

How can I achieve the same using the new AggregationBuilder for the Java API Client ?

```auto
Aggregation term2 = AggregationBuilders.terms().name("agg1").field("test").build()._toAggregation();

Aggregation filterAgg = AggregationBuilders.filter().matchAll(QueryBuilders.matchAll().build()).build()._toAggregation();

```

Now I need to add subAggregation 'term' to 'filterAgg' that I'm not able to figure out

---

<div class="post-metadata">

**Author:** ![RabBit\_BR](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rabbit_br/32/82261_2.png) [@RabBit\_BR](https://discuss.elastic.co/u/RabBit_BR)\
**Post date:** [September 1, 2022, 4:29pm UTC](https://discuss.elastic.co/t/sub-aggregation-in-new-java-api-client/313447/2 "2022-09-01T16:29:34Z")

</div>

Hi @Sarthak_Agarwal

Look this example, maybe help you.

```auto
    Map<String, Aggregation> map = new HashMap<>();

    Aggregation subAggregation = new Aggregation.Builder()
        .avg(new AverageAggregation.Builder().field("revenue").build())
        .build();

    Aggregation aggregation = new Aggregation.Builder()
        .terms(new TermsAggregation.Builder().field("director.keyword").build())
        .aggregations(new HashMap<>() {{
          put("avg_renevue", subAggregation);
        }}).build();

    map.put("agg_director", aggregation);

    SearchRequest searchRequest = new SearchRequest.Builder()
        .index("idx_name")
        .size(0)
        .aggregations(map)
        .build();

```

---

<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:** [September 29, 2022, 4:30pm UTC](https://discuss.elastic.co/t/sub-aggregation-in-new-java-api-client/313447/3 "2022-09-29T16:30:13Z")

</div>

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