ES的RestHighLevelClient的聚合查询

对ES的某字段聚合求SUM,按时间字段来分组,ES的版本是7.5

/获取连接
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("your ip", 9200, "http")));
//设置索引
SearchRequest searchRequest = new SearchRequest("your index");
//构建查询
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery("text","test");
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("Time");
//起始时间
rangeQueryBuilder.gte("2020-04-01T00:00:00+08:00");
//结束时间
rangeQueryBuilder.lte("2020-04-31T23:59:59+08:00");
boolBuilder.must(matchQueryBuilder1).must(rangeQueryBuilder);
sourceBuilder.query(boolBuilder);

//按时间聚合,求TX的和
//DateHistogramInterval.minutes(5)是指按5分钟聚合
//format("yyyy-MM-dd HH:mm")是指聚合的结果的Time的格式
//BucketOrder.aggregation("tx_sum", false)对聚合结果的排序 true为正序 false为倒序
AggregationBuilder aggregation = AggregationBuilders.dateHistogram("time_count").field("Time").fixedInterval(DateHistogramInterval.minutes(5)).format("yyyy-MM-dd HH:mm")
	.order(BucketOrder.aggregation("tx_sum", false));
aggregation.subAggregation(AggregationBuilders.sum("tx_sum").field("Tx"));
sourceBuilder.aggregation(aggregation);

searchRequest.source(sourceBuilder);
//发送请求
SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);

//获取聚合的结果
Map<String,Double> map = new LinkedHashMap<>();
Aggregations aggregations = searchResponse.getAggregations();
Aggregation aggregation1 = aggregations.get("time_count");
List<? extends Histogram.Bucket> buckets = ((Histogram)aggregation1).getBuckets();
for (Histogram.Bucket bucket : buckets){
	String keyAsString = bucket.getKeyAsString();
	Sum sum = bucket.getAggregations().get("tx_sum");
	map.put(keyAsString,sum.getValue());
}

你可能感兴趣的:(elasticsearch,java)