elasticsearch aggregation 聚合统计
在项目中可以通过聚合统计数据,常用的平均值计算(avg),求和 (sum),数量统计(count) ,最大值(max) 最小值(min)等 ,可以直接通过Aggregation得到计算结果
计算平均值 avg
GET company/user/_search { "aggs": { "maxname": { "avg": { "field": "age" } } } }
public void avg(){
AvgAggregationBuilder avgAggregationBuilder =AggregationBuilders.avg("avg").field("age");
SearchQuery searchQuery =new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("uid","1"))
.addAggregation(avgAggregationBuilder)
.build();
elasticsearchTemplate.query(searchQuery,searchResponse -> {
Avg avg =searchResponse.getAggregations().get("avg");
System.out.println(avg.getValue());
return null;
});
}
统计某一字段数量 avg
GET company/user/_search { "aggs": { "maxname": { "value_count": { "field": "age" } } } }
public void avg(){
ValueCountAggregationBuilder countAggregationBuilder =AggregationBuilders.count("count").field("age");
SearchQuery searchQuery =new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("uid","1"))
.addAggregation(countAggregationBuilder)
.build();
elasticsearchTemplate.query(searchQuery,searchResponse -> {
ValueCount count =searchResponse.getAggregations().get("count");
System.out.println(count.getValue());
return null;
});
}