public Map<String, Object> getCountGroup(String index,String startTime,String endTime,String groupFiled) throws IOException {
Map<String, Object> resultMap = new HashMap<String, Object>(16);
SearchRequest searchRequest = new SearchRequest(index);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
SearchSourceBuilder builder = new SearchSourceBuilder();
boolQueryBuilder.must(QueryBuilders.termsQuery("字段" + ".keyword", 值));
boolQueryBuilder.mustNot(QueryBuilders.termsQuery("字段" + ".keyword", 值));
if (StringUtils.isNotBlank(startTime)) {
boolQueryBuilder.must(QueryBuilders.rangeQuery("startTime"+".keyword").from(startTime));
}
if (StringUtils.isNotBlank(endTime)) {
boolQueryBuilder.must(QueryBuilders.rangeQuery("startTime"+".keyword").to(endTime));
}
builder.query(boolQueryBuilder);
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("count")
.field(groupFiled + ".keyword");
builder.aggregation(aggregationBuilder);
searchRequest.source(builder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
Terms terms = response.getAggregations().get("count");
for (Terms.Bucket bucket : terms.getBuckets()) {
resultMap.put(bucket.getKey().toString(), bucket.getDocCount());
}
return resultMap;
}
分组相关语句为:
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("count")
.field("分组字段"+ ".keyword");
builder.aggregation(aggregationBuilder);
|