Elasticsearch java api client

{
  "aggs": {
    "my-agg-name": {
      "terms": {
        "field": "my-field"
      },
      "aggs": {
        "my-sub-agg-name": {
          "avg": {
            "field": "my-other-field"
          }
        }
      }
    }
  }
}

I wanted to perform the above Elasticsearch query in java using the new Elasticsearch java api client . I am using Elasticsearch version 7.16 . Can someone please help me in building the same query using the new Elasticsearch java api client .

That should be:

SearchRequest search = SearchRequest.of(b1 -> b1
    .aggregations("my-agg-name", b2 -> b2
        .terms(b3 -> b3
            .field("my-field")
        )
        .aggregations("my-sub-agg-name", b3 -> b3
            .avg(b4 -> b4
                .field("my-other-field")
            )
        )
    )
);
1 Like

Hi @swallez ,
This looks perfect . Just one more doubt the of function is available for 7.16 and not for 7.15 version . If possible can you please share a solution which can be used for 7.15 as well .
Thanks in Advance .

The SomeClass.of method is a shortcut for new SomeClass.Builder() at the begining and .build() at the end:

SearchRequest search = new SearchRequest.Builder()
    .aggregations("my-agg-name", b2 -> b2
        .terms(b3 -> b3
            .field("my-field")
        )
        .aggregations("my-sub-agg-name", b3 -> b3
            .avg(b4 -> b4
                .field("my-other-field")
            )
        )
    )
    .build();

Thank you so much for clarification @swallez .

Hi @swallez ,
With the above solution i could see query getting created correctly but i am getting below error in runtime .

co.elastic.clients.base.ApiException: null
	at co.elastic.clients.base.rest_client.RestClientTransport.getHighLevelResponse(RestClientTransport.java:224)
	at co.elastic.clients.base.rest_client.RestClientTransport.performRequest(RestClientTransport.java:104)
	at co.elastic.clients.elasticsearch.ElasticsearchClient.search(ElasticsearchClient.java:1283)
	

What version are you using? The stacktrace seems to indicate version 7.15.

Version 7.15 was a beta version which is not supported. Please upgrade to version 7.16.2

Yes the issue got resolved while using 7.16.2 . Mapping aggregations from search response also seems to changed. Can you please help me with mapping aggregation values from search response as well ?

The API to create an aggregation may not be straightfoward, but for results just follow the API and the completion provided by your IDE.