使用ElasticsearchTemplate和聚合器获取聚合价值

时间:2018-07-10 12:27:24

标签: java spring-boot elasticsearch

我在提取汇总值时遇到问题。

配置是带有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");

如何提取值?也许有更好的方法?

1 个答案:

答案 0 :(得分:0)

    for (Aggregation aggs : aggregations) {

         Sum sum = (Sum) aggs;
         double sumValue = sum.getValue();
          System.out.println("sumValue=" + sumValue);
  }