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`。
代码实现部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端