public RestResult fileChart(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 搜索源构建对象
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermsAggregationBuilder aggregationBuilder = AggregationBuilders
.terms("file_tr").field("file_time")// 桶分组
.size(50)
.subAggregation(AggregationBuilders.sum("file_sum").field("file_size"));// 求和
searchSourceBuilder.aggregation(aggregationBuilder);
// 不输出原始数据
//searchSourceBuilder.size(0);
// 打印dsl语句
log.info("dsl:" + searchSourceBuilder.toString());
// 搜索请求对象
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("file");
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
log.error("IOException:",e);
return RestResponse.failed("");
}
Map<String,Object> result = new HashMap<>();
Aggregations aggregations = searchResponse.getAggregations();
ParsedDoubleTerms parsedDoubleTerms = aggregations.get("file_tr");
List<? extends Terms.Bucket> buckets = parsedDoubleTerms.getBuckets();
for (Terms.Bucket bucket : buckets) {
//time
String key = new BigDecimal(String.valueOf(((double) bucket.getKey()) * 1000))
.toPlainString().split("\\.")[0];
String formatTime = dateFormat.format(new Date(Long.parseLong(key)));
long docCount = bucket.getDocCount();
//获取数据
Aggregations bucketAggregations = bucket.getAggregations();
ParsedSum sum = bucketAggregations.get("file_sum");
result.put("time",formatTime);
result.put("docCount",docCount);
result.put("sum",sum.getValue());
System.out.println(formatTime + ":" + docCount + "__" + sum.getValue());
}
return RestResponse.success(result);
}
网友评论