es的时间聚合date_histogram
{ // 不显示具体的内容 "size": 0, // 聚合 "aggs": { // 自己取的聚合名字 "group_by_grabTime": { // es提供的时间处理函数 "date_histogram": { // 需要聚合分组的字段名称, 类型需要为date, 格式没有要求 "field": "createDate", // 按什么时间段聚合, "calendar_interval": "day", // 设置时区, 这样就相当于东八区的时间 "time_zone":"+08:00", // 返回值格式化,HH大写,不然不能区分上午、下午 "format": "yyyy-MM-dd", // 为空的话则填充0 "min_doc_count": 0, // 需要填充0的范围 "extended_bounds": { "min": 1663570845000, "max": 1664175645000 } }, // 聚合 "aggs": { // 自己取的名称 "group_by_status": { // es提供 "terms": { // 聚合字段名 "field": "account" } } } } } }
例子以根据时间查询账号的登录情况,返回结果:

date_histogra 聚集以时间为间隔定义日期范围,字段值具有相同日期范围的 文档将落入同一桶中。同样,返回结果中也会包含每个间隔范围内的文档数量 doc_count。
calendar_interval 支持 1 年、 1 季度、 1 月、 1 周、 1 天、 1 小时、 1 分钟,不支持时间为复数,
fixed_interval 支持的时间单位为天、小时、分、秒、 毫秒,允许复数,例如"fixed_interval" : "30d" ,表示为 30 天。
interval字段支持多种关键字:`year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`。
代码实现部分:
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(indexName);
DateHistogramAggregationBuilder aggregation = AggregationBuilders.dateHistogram("createDate")
.field("createDate")
.calendarInterval(DateHistogramInterval.DAY)
.format("yyyy-MM-dd")
.timeZone(ZoneId.of("+08:00"))
//过滤掉count为0的数据
.minDocCount(1)
.subAggregation(aggregationBuilder);
SearchResponse response;
try {
response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
log.info("response is {}", response);
if (response != null) {
Histogram byAgeAggregation = response.getAggregations().get("createDate");
for (Histogram.Bucket buck : byAgeAggregation.getBuckets()) {
Aggregations bucketAggregations = buck.getAggregations();
// buck.getDocCount();
// buck.getKeyAsString();
}
}

浙公网安备 33010602011771号