elasticsearch 按时间分组聚合
按时间分组聚合
过去一小时5分钟(Inbound,Outbound)平均值:
"aggregations": { "group_by_time": { "aggregations": { "Inbound": { "avg": { "field": "Inbound" "Outbound": { "avg": { "field": "Outbound" "date_histogram": { "field": "Time", "format": "yyyy-MM-dd HH:mm:ss", "interval": "5m", "min_doc_count": 0, "time_zone": "+08:00" "query": { "bool": { "must": [{ "range": { "Time": { "from": "2020-04-28T14:16:32.9832859+08:00", "include_lower": true, "include_upper": true, "to": "2020-04-28T15:16:32.9832859+08:00" "range": { "Inbound": { "from": 0, "include_lower": true, "include_upper": true, "to": null "range": { "Outbound": { "from": 0, "include_lower": true, "include_upper": true, "to": null "term": { "LinkId": 15 "size": 1 //小时;大于等于结束时间,小于等于(结束时间-一小时) startTime = endTime.Add(-time.Hour * 1) query := elastic.NewBoolQuery() //查询过去一小时数据 query.Must(elastic.NewRangeQuery("Time").Gte(startTime).Lte(endTime)) query.Must(elastic.NewRangeQuery("Inbound").Gte(0)) query.Must(elastic.NewRangeQuery("Outbound").Gte(0)) query.Must(elastic.NewTermQuery("LinkId", reqParam.LinkId)) //需要时间聚合分组的字段名称, 类型需要为date, 格式没有要求 aggField := "Time" //时间分组间隔;默认5分钟平均值 aggInterval := "5m" // 返回值格式化,HH大写,不然不能区分上午、下午 aggFormat := "yyyy-MM-dd HH:mm:ss" // 为空的话则填充0 aggMinDocCount := int64(0) //设置时区, 这样就相当于东八区的时间 aggTimeZone := "+08:00" aggs := elastic.NewDateHistogramAggregation(). Field(aggField). Interval(aggInterval). Format(aggFormat). MinDocCount(aggMinDocCount). TimeZone(aggTimeZone) //.Offset("+6h") //sub Aggregation sumAggInbound := elastic.NewAvgAggregation().Field("Inbound") aggs.SubAggregation("Inbound", sumAggInbound) sumAggOutbound := elastic.NewAvgAggregation().Field("Outbound")