首页  编辑  

SpringBoot + ElasticSearch聚合搜索

Tags: /Java/   Date Created:
ElasticSearch的构造是:
1. 如果要使用where过滤数据,首先要构造RangeQuery或者BooleanQuery等专门用于过滤的QueryBuilder
2. 如果要对数据进行分组,则构造AggregationBuilder,如果在这个基础上还要构造count, sum等,则需要利用subAggregation。
例如对时间进行按天聚合后再统计每天的数据计数,代码如下:
public class CLAPResult {
/**
* timeStamp 请求完成时的时间戳,Unix 时间戳
*/
// @Field(type = FieldType.Date)
public String timeStamp;

public Long count;

}
        public List<CLAPResult> countByDay(Date start, Date end) {
        // 类似SQL语句
// select date(timeStamp) as 日期, count(*) as 总数
// from performances
// where timeStamp between start and end
// group by 日期
// order by 日期
List<CLAPResult> ret = new ArrayList<>();
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

// count(xxx),如果要 count(distinct),使用 .cardinality 替代 count
ValueCountAggregationBuilder count = AggregationBuilders.count("总数").field("_id");

// timeStamp between 开始时间 and 结束时间
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("timeStamp").gte(start).lte(end);

AggregationBuilder group = AggregationBuilders // group by
.dateHistogram("日期")
.fixedInterval(DateHistogramInterval.days(1))
.minDocCount(0) // 返回空桶
.field("timeStamp")
// .offset("-8h")
.format("yyyy-MM-dd")
.subAggregation(count);
sourceBuilder.query(rangeQuery).aggregation(group).sort("timeStamp", SortOrder.DESC);

searchRequest.source(sourceBuilder);
RequestOptions options = RequestOptions.DEFAULT;
try {
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, options);

Aggregations aggregations = searchResponse.getAggregations();
Histogram histogram = aggregations.get("日期");
List<? extends Histogram.Bucket> buckets = histogram.getBuckets();
for (Histogram.Bucket bucket : buckets) {
CLAPResult item = new CLAPResult();
item.timeStamp = bucket.getKeyAsString();
Aggregation aggregation = bucket.getAggregations().get("总数");
if (aggregation instanceof ParsedValueCount) {
ParsedValueCount valueCount = (ParsedValueCount) aggregation;
item.count = valueCount.getValue();
}
ret.add(item);
}
} catch (IOException e) {
Log.debug("PagePerformanceServiceImpl.findByUrl() 错误: " + e.getMessage());
}

return ret;
}