我在提取汇总值时遇到问题。
配置是带有spring-boot-starter-data-elasticsearch的spring。
文档用户在数据库中被索引多次。
我想返回字段“commentsCnt”的总和
@Autowired
ElasticsearchTemplate elasticsearchTemplate;
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withIndices("comment")
.withQuery(matchQuery("user", userName))
.addAggregation(AggregationBuilders.sum("sum_of_comments").field("commentsCnt"))
.build();
Aggregations aggregations = elasticsearchTemplate.query(searchQuery,
new ResultsExtractor<Aggregations>() {
@Override
public Aggregations extract(SearchResponse response) {
return response.getAggregations();
}
});
Aggregation ret = aggregations.get("sum_of_comments");
如何提取值(value)?也许有更好的方法?
最佳答案
for (Aggregation aggs : aggregations) {
Sum sum = (Sum) aggs;
double sumValue = sum.getValue();
System.out.println("sumValue=" + sumValue);
}