Terms 按字段的值進行分類,並計算出doc_count,html
bucket聚合 相似於 group byjson
經常使用統計 分類並出現頻率高的,並進一步挖出,計算出想要的數據。curl
參考資料elasticsearch
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html ide
1.批量插入數據ui
curl -XPOST 127.0.0.1:9200/cars/transactions/_bulk --data-binary @cars.json url
{ "index": {}} { "price" : 10000, "color" : "red", "make" : "honda", "sold" : "2014-10-28" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" } { "index": {}} { "price" : 30000, "color" : "green", "make" : "ford", "sold" : "2014-05-18" } { "index": {}} { "price" : 15000, "color" : "blue", "make" : "toyota", "sold" : "2014-07-02" } { "index": {}} { "price" : 12000, "color" : "green", "make" : "toyota", "sold" : "2014-08-19" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" } { "index": {}} { "price" : 80000, "color" : "red", "make" : "bmw", "sold" : "2014-01-01" } { "index": {}} { "price" : 25000, "color" : "blue", "make" : "ford", "sold" : "2014-02-12" }
2.哪一種顏色的車賣的最好
http://192.168.1.10:9200/cars/
_search?search_type=count //並不關心搜索結果,只關心統計,使用的search_type是countspa
1 { "aggs": { 3 "color": { 4 "terms": { //定義了一個terms類型的桶,它針對color字段聚合,terms桶會動態地爲每個它遇到的不重複的詞條建立一個新的桶 5 "field": "color", 6 "size": 50, //返回結果大小 7 "min_doc_count": 1, //控制最小計數 大於1才顯示 8 "order": {"_count": "asc" } //排序方式 11 } 12 } 13 } 14 }
//每一個桶中的key對應的是在color字段中找到的不重複的詞條。它同時也包含了一個doc_count,用來表示包含了該詞條的文檔數量。
//響應包含了一個桶列表,每一個桶都對應着一個不重複的顏色(好比,紅色或者綠色)。每一個桶也包含了「掉入」該桶中的文檔數量。好比,有4輛紅色的車3d
3.每種顏色汽車的平均價格是多少?code
{ "aggs": { "color": { "terms": { "field": "color", "size": 50, "min_doc_count": 1, "order": { "avg_price": "asc" } //按平均價格排序 }, "aggs": { //添加了一個新的aggs層級(聚合層)avg 指標嵌套在terms桶中,每種顏色都計算一個平均值 "avg_price": { "avg": { "field": "price" } } } } } }
返回每一個顏色汽車的個數及平均價格
4.每種顏色的汽車的製造商分佈信息?
{"aggs": { "color": { "terms": { "field": "color", "size": 50, "min_doc_count": 1, "order": {"avg_price": "asc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make": { //添加了新聚合make,它是一個terms類型的桶(嵌套在名爲colors的terms桶中)。這意味着會根據數據集建立不重複的(color, make)組合 "terms": { "field": "make" } } } } } }
4.再添加 每一個製造商 最低和最高價格?
{ "aggs": { "color": { "terms": { "field": "color", "size": 50, "min_doc_count": 1, "order": { "avg_price": "asc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make": { "terms": { "field": "make"}, "aggs": { "min_price": { "min": { "field": "price" } }, "max_price": { "max": { "field": "price" } } } } } } } }
5.再添加 每一個製造商 價格列表?
{ "aggs": { "color": { "terms": { "field": "color", "size": 50, "min_doc_count": 1, "order": { "avg_price": "asc" } }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make": { "terms": { "field": "make" }, "aggs": { "price": { "terms": { "field": "price" } }, "min_price": { "min": { "field": "price" } }, "max_price": { "max": { "field": "price" } } } } } } } }