阶梯分组
劃分桶的其它方式
前面講了,劃分桶的方式有很多,例如:
-
Date Histogram Aggregation:根據(jù)日期階梯分組,例如給定階梯為周,會自動每周分為一組
-
Histogram Aggregation:根據(jù)數(shù)值階梯分組,與日期類似
-
Terms Aggregation:根據(jù)詞條內(nèi)容分組,詞條內(nèi)容完全匹配的為一組
-
Range Aggregation:數(shù)值和日期的范圍分組,指定開始和結(jié)束,然后按段分組
剛剛的案例中,我們采用的是Terms Aggregation,即根據(jù)詞條劃分桶。
接下來,我們再學(xué)習(xí)幾個比較實用的:
階梯分桶Histogram
原理:
histogram是把數(shù)值類型的字段,按照一定的階梯大小進行分組。你需要指定一個階梯值(interval)來劃分階梯大小。
舉例:
比如你有價格字段,如果你設(shè)定interval的值為200,那么階梯就會是這樣的:
0,200,400,600,...
上面列出的是每個階梯的key,也是區(qū)間的啟點。
如果一件商品的價格是450,會落入哪個階梯區(qū)間呢?計算公式如下:
bucket_key = Math.floor((value - offset) / interval) * interval + offsetvalue:就是當前數(shù)據(jù)的值,本例中是450
offset:起始偏移量,默認為0
interval:階梯間隔,比如200
因此你得到的key = Math.floor((450 - 0) / 200) * 200 + 0 = 400
操作一下:
比如,我們對汽車的價格進行分組,指定間隔interval為5000:
GET /cars/_search {"size":0,"aggs":{"price":{"histogram": {"field": "price","interval": 5000}}} }結(jié)果:
{"took": 21,"timed_out": false,"_shards": {"total": 5,"successful": 5,"skipped": 0,"failed": 0},"hits": {"total": 8,"max_score": 0,"hits": []},"aggregations": {"price": {"buckets": [{"key": 10000,"doc_count": 2},{"key": 15000,"doc_count": 1},{"key": 20000,"doc_count": 2},{"key": 25000,"doc_count": 1},{"key": 30000,"doc_count": 1},{"key": 35000,"doc_count": 0},{"key": 40000,"doc_count": 0},{"key": 45000,"doc_count": 0},{"key": 50000,"doc_count": 0},{"key": 55000,"doc_count": 0},{"key": 60000,"doc_count": 0},{"key": 65000,"doc_count": 0},{"key": 70000,"doc_count": 0},{"key": 75000,"doc_count": 0},{"key": 80000,"doc_count": 1}]}} }你會發(fā)現(xiàn),中間有大量的文檔數(shù)量為0 的桶,看起來很丑。
我們可以增加一個參數(shù)min_doc_count為1,來約束最少文檔數(shù)量為1,這樣文檔數(shù)量為0的桶會被過濾
示例:
GET /cars/_search {"size":0,"aggs":{"price":{"histogram": {"field": "price","interval": 5000,"min_doc_count": 1}}} }結(jié)果:
{"took": 15,"timed_out": false,"_shards": {"total": 5,"successful": 5,"skipped": 0,"failed": 0},"hits": {"total": 8,"max_score": 0,"hits": []},"aggregations": {"price": {"buckets": [{"key": 10000,"doc_count": 2},{"key": 15000,"doc_count": 1},{"key": 20000,"doc_count": 2},{"key": 25000,"doc_count": 1},{"key": 30000,"doc_count": 1},{"key": 80000,"doc_count": 1}]}} }完美,!
如果你用kibana將結(jié)果變?yōu)橹螆D,會更好看:
范圍分桶range
范圍分桶與階梯分桶類似,也是把數(shù)字按照階段進行分組,只不過range方式需要你自己指定每一組的起始和結(jié)束大小。
總結(jié)
- 上一篇: 聚合
- 下一篇: 搭建elasticsearch测试工程