gpt4 book ai didi

java - 使用 Java 的 ElasticSearch 聚合

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:12 25 4
gpt4 key购买 nike

我想在我的 java 应用程序中进行聚合。

首先,我用 curl 构造了 REST 查询。它看起来像:

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"
}
}
}
}
}
}
'

如我所料返回结果

enter image description here

之后我用 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() + " ");
}

问题是:

如何获取当前桶项的“contract_sum”聚合值?

当我在 IntelliJ Idea 中使用调试工具时,它似乎可以

enter image description here

请帮我写代码示例。

最佳答案

我和我的网友一起找到了解决办法

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()));
}

关于java - 使用 Java 的 ElasticSearch 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com