I want to get aggregation in my java application.
First of all I've constracted REST query with curl. It's looks like:
curl -XGET 'localhost:9200/analysis/_search?pretty' -H 'Content-Type:
application/json' -d'
{
"size": 0,
"query" : {
"bool": {
"must": [
{ "term" : { "customer_id" : 5117 } }
]
}
},
"aggs": {
"customer_id": {
"terms": {
"field": "customer_id",
"order": {
"contract_sum": "desc"
}
},
"aggs": {
"contract_sum": {
"sum": {
"field": "contract_sum"
}
}
}
}
}
}
'
It returned result as I expected
After that I've created some code in java
Settings settings = Settings.builder().put("cluster.name", elasticProperties.getElasticClusterName()).build();
log.info("Initializing ElasticSearch client");
try (TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(
InetAddress.getByName(elasticProperties.getElasticTransportAddress()), elasticProperties.getElasticTransportPort()))) {
// Base query
log.info("Preparing query");
SearchRequestBuilder requestBuilder = client.prepareSearch(elasticProperties.getElasticIndexName())
.setTypes(elasticProperties.getElasticTypeName())
.setSize(Top);
// Add aggregations
AggregationBuilder aggregation =
AggregationBuilders
.terms("customer_id")
.field("customer_id")
//.order(Terms.Order.aggregation("customer_id", "contract_sum", false))
.subAggregation(
AggregationBuilders.sum("total_contract_sum")
.field("contract_sum")
);
requestBuilder.addAggregation(aggregation);
// Get response
log.info("Executing query");
SearchResponse response = requestBuilder.get();
log.info("Query results:");
Terms contractSums = response.getAggregations().get("customer_id");
for (Terms.Bucket bucket : contractSums.getBuckets()) {
log.info(" " + bucket.getKey() + " ");
}
The question is:
How to get "contract_sum" aggregation value for current bucket item?
When I use debug tool in IntelliJ Idea it seems that it can
Please help me with code example.
I've found solution with my Internet friends
log.info("Query results:");
Terms contractSums = response.getAggregations().get("customer_id");
for (Terms.Bucket bucket : contractSums.getBuckets()) {
Sum aggValue = bucket.getAggregations().get("total_contract_sum");
DecimalFormat formatter = new DecimalFormat("0.00");
log.info(" " + bucket.getKey() + " " + formatter.format(aggValue.getValue()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With