AggregationBuilders.dateHistogram 可以按时间跨度聚合数据
查询语句,统计每天的浏览量
--聚合条件为
DateHistogramAggregationBuilder dateHistogramAgg = AggregationBuilders.dateHistogram("groupDate").field("time")
.dateHistogramInterval(DateHistogramInterval.DAY).offset("-8h").minDocCount(0);
GET behavior_log/behavior_log/_search
{
"size": 0,
"query": {
"bool": {
"must": [
{
"term" : {
"event" : "view"
}
},
{
"range": {
"time": {
"gte": 1578585600000,
"lt": 1578931200000
}
}
}]
}
},
"aggs": {
"groupDate": {
"date_histogram": {
// 需要聚合分组的字段名称
"field": "time",
// 为空的话则填充0
"min_doc_count" : 0,
//按什么时间段聚合,这里是1天
"interval": "1d",
//偏移量,由于默认东八区,而time字段是long的,所以统计时间都从8:00开始,所以需要减去
"offset": "-8h"
}
}
},
"sort" : [
{
"time" : {
"order" : "asc"
}
}
]
}
返回结果
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 378,
"max_score": 0,
"hits": []
},
"aggregations": {
"groupDate": {
"buckets": [
{
"key": 1578585600000,
"doc_count": 155
},
{
"key": 1578672000000,
"doc_count": 5
},
{
"key": 1578758400000,
"doc_count": 168
},
{
"key": 1578844800000,
"doc_count": 50
}
]
}
}
}