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等都是支持的。