Elasticsearch的聚合主要分红两大类:metric和bucket,2.0中新增了pipeline尚未研究。本篇仍是来介绍Bucket聚合中的经常使用聚合——date histogram.参考:官方文档html
Date histogram的用法与histogram差很少,只不过区间上支持了日期的表达式。ide
{ "aggs":{ "articles_over_time":{ "date_histogram":{ "field":"date", "interval":"month" } } } }
interval字段支持多种关键字:`year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`ui
固然也支持对这些关键字进行扩展使用,好比一个半小时能够定义成以下:code
{ "aggs":{ "articles_over_time":{ "date_histogram":{ "field":"date", "interval":"1.5h" } } } }
返回的结果能够经过设置format进行格式化:orm
{ "aggs":{ "articles_over_time":{ "date_histogram":{ "field":"date", "interval":"1M", "format":"yyyy-MM-dd" } } } }
获得的结果以下:htm
{ "aggregations":{ "articles_over_time":{ "buckets":[{ "key_as_string":"2013-02-02", "key":1328140800000, "doc_count":1 },{ "key_as_string":"2013-03-02", "key":1330646400000, "doc_count":2 }, ... ]} } }
其中key_as_string是格式化后的日期,key显示了是日期时间戳,ip
在es中日期支持时区的表示方法,这样就至关于东八区的时间。文档
{ "aggs":{ "by_day":{ "date_histogram":{ "field":"date", "interval":"day", "time_zone":"+08:00" } } } }
默认状况是从凌晨0点到午夜24:00,若是想改变时间区间,能够经过下面的方式,设置偏移值:get
{"aggs":{ "by_day":{ "date_histogram":{ "field":"date", "interval":"day", "offset":"+6h" } } } }
那么桶的区间就改变为:string
"aggregations":{ "by_day":{ "buckets":[{ "key_as_string":"2015-09-30T06:00:00.000Z", "key":1443592800000, "doc_count":1 },{ "key_as_string":"2015-10-01T06:00:00.000Z", "key":1443679200000, "doc_count":1 }] } }
当遇到没有值的字段,就会按照缺省字段missing value来计算:
{ "aggs":{ "publish_date":{ "date_histogram":{ "field":"publish_date", "interval":"year", "missing":"2000-01-01" } } } }
对于其余的一些用法,这里就不过多赘述了,好比脚本、Order、min_doc_count过滤,extended_bounds等都是支持的。