# Any Sample Java API client dynamic nested aggregation query building

**URL:** <https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897>\
**Category:** Elasticsearch\
**Created:** [April 22, 2024, 9:46am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897 "2024-04-22T09:46:41Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![prasad.ram1431](https://avatars.discourse-cdn.com/v4/letter/p/c89c15/32.png) [@prasad.ram1431](https://discuss.elastic.co/u/prasad.ram1431)\
**Post date:** [April 22, 2024, 9:46am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/1 "2024-04-22T09:46:41Z")

</div>

Hi Team,

I have below query with me for which I am trying to build dynamically using Java API client.

```auto
{
"aggs": {
    "country_aggr": {
      "terms": {
        "field": "country",
        "size": 1000
      },
      "aggs": {
        "state_aggr": {
          "terms": {
            "field": "state",
              "size": 1000
          },
          "aggs": {
            "city_aggr": {
              "terms": {
                "field": "city",
                "size": 1000
              }
            }
          }
        }
      }
    }
  }
}

```

Any help would be appreciated.

Thanks,  
Ram Prasad

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [April 22, 2024, 2:48pm UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/2 "2024-04-22T14:48:33Z")

</div>

Have a look at [Switching from the Java High Level Rest Client to the new Java API Client | Elastic Blog](https://www.elastic.co/fr/blog/switching-from-the-java-high-level-rest-client-to-the-new-java-api-client)

This might help you to find how to build your code.

An example of on agg in Java is also available at:

> <https://github.com/dadoonet/elasticsearch-java-client-demo/blob/main/src/test/java/fr/pilato/test/elasticsearch/hlclient/EsClientIT.java#L393-L409>

If you don't succeed, let us know and share what you did so far so we can iterate from that.

---

<div class="post-metadata">

**Author:** ![prasad.ram1431](https://avatars.discourse-cdn.com/v4/letter/p/c89c15/32.png) [@prasad.ram1431](https://discuss.elastic.co/u/prasad.ram1431)\
**Post date:** [April 23, 2024, 9:15am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/3 "2024-04-23T09:15:32Z")

</div>

Hi dadoonet,

We are using Java API client. Currently we are preparing parent-child hierarchy based aggregation upfront using String (its not a recommended way) for different levels.  
We tried to build this hierarchy dynamically based on the total number of fields, like below.

```auto
Aggregation aggr = Aggregation.of(t0 -> t0.terms(f0 -> f0.field(fields[0]).size(fieldSize[0])).aggregations(fields[1],
				t1 -> t1.terms(f1 -> f1.field(fields[1]).size(fieldSize[1])).aggregations(fields[2],
						t2 -> t2.terms(f2 -> f2.field(fields[2]).size(fieldSize[2])))));

```

But our requirement is, sub-aggregation should be appended to main aggregation within the iteration of fields.

Kindly let me know if my requirement is not clear.

Thanks,  
Ram Prasad G

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [April 23, 2024, 11:32am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/4 "2024-04-23T11:32:23Z")

</div>

How should this look like using the QueryDSL?

---

<div class="post-metadata">

**Author:** ![prasad.ram1431](https://avatars.discourse-cdn.com/v4/letter/p/c89c15/32.png) [@prasad.ram1431](https://discuss.elastic.co/u/prasad.ram1431)\
**Post date:** [April 24, 2024, 5:35am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/5 "2024-04-24T05:35:12Z")

</div>

It should look something like this,

```auto
Aggregation cityAggr = new Aggregation.Builder()
		.terms(new TermsAggregation.Builder().field(CITY).build())
		.build();
Map<String, Aggregation> cityAggrMap = new HashMap<>();
cityAggrMap.put(CITY_AGGR, cityAggr);

Aggregation stateAggr = new Aggregation.Builder()
		.terms(new TermsAggregation.Builder().field(STATE).build()).aggregations(cityAggrMap)
		.build();
Map<String, Aggregation> stateAggrMap = new HashMap<>();
stateAggrMap.put(STATE_AGGR, stateAggr);

Aggregation countryAggr = new Aggregation.Builder()
		.terms(new TermsAggregation.Builder().field(COUNTRY).build()).aggregations(stateAggrMap)
		.build();
Map<String, Aggregation> countryAggrMap = new HashMap<>();
countryAggrMap.put(COUNTRY_AGGR, countryAggr);

SearchRequest searchReq = SearchRequest.Builder().index(collection_name).size(0)
		.aggregations(countryAggrMap)
		.build();

```

In the above code, I am framing manually for 3 level of nested aggregation. This I need to frame dynamically.

Thanks,  
Ram Prasad G

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [April 26, 2024, 9:47am UTC](https://discuss.elastic.co/t/any-sample-java-api-client-dynamic-nested-aggregation-query-building/357897/6 "2024-04-26T09:47:34Z")

</div>

So you want something like this:

```auto
SearchResponse<Void> response = client.search(sr -> sr
                .index(indexName)
                .aggregations("country", a -> a.terms(ta -> ta.field("country"))
                        .aggregations("state", sa -> sa.terms(ta -> ta.field("state"))
                                .aggregations("city", ca -> ca.terms(ta -> ta.field("city")))
                        )
                )
        , Void.class);

```

But built depending on some conditions?
