Method 1 (recommended)
make sure to import:
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.dsl.SearchRequest;
import org.elasticsearch.client.dsl.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
then inside your code write this:
// Construct the search request
SearchRequest searchRequest = new SearchRequest("your_index");
searchRequest.source(sourceBuilder -> sourceBuilder.query(QueryBuilders.matchAllQuery()) // Add a query to match all documents
.aggregations(aggregationBuilder -> aggregationBuilder
.terms("my-agg-name", term -> term.field("my-field")) // Add an aggregation named "my-agg-name" of type terms to group documents by the value of "my-field"
// Now we have a number of groups and we will add the sub-aggregation to them
.aggregations(subAggregationBuilder -> subAggregationBuilder
.avg("my-sub-agg-name", avg -> avg.field("my-other-field"))))); // Add a sub-aggregation named "my-sub-agg-name" of type avg to calculate the average of "my-other-field"
// Execute the search request and retrieve the search response
SearchResponse<Void> searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);//assuming that you already defined a client
// You can handle the search response by using it directly
System.out.println(searchResponse);
Method 2 (not recommended)
I will share another method it is not recommended but useful if you can't do your code using the java-client, you still can use your basic query by:
// Define your query, for example in your case the aggregation will be
String query = "{\n" +
" \"aggs\": {\n" +
" \"my-agg-name\": {\n" +
" \"terms\": {\n" +
" \"field\": \"my-field\"\n" +
" },\n" +
" \"aggs\": {\n" +
" \"my-sub-agg-name\": {\n" +
" \"avg\": {\n" +
" \"field\": \"my-other-field\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
// Create the request
Request request = new Request("POST", "/your_index/_search");
// Add your query to the request
request.setJsonEntity(query);
// Execute the request
Response response = client.getLowLevelClient().performRequest(request);
// This will print JSON file that has all the data, it will look like the Elasticsearch response exactly
System.out.println(response.getEntity().getContent());
// You can extract the average by parsing the JSON response