参考资料:
https://elasticsearch.cn/book/elasticsearch_definitive_guide_2.x/_combining_the_two.html
特定概念:
桶(Buckets)满足特定条件的文档的集合
指标(Metrics)对桶内的文档进行统计计算
SELECT COUNT(color)
FROM table
GROUP BY color
COUNT(color)
相当于指标。
GROUP BY color
相当于桶。
聚合例子:
curl -XGET 'localhost:9200/text/_search?pretty' -d ' {"size":0, "aggs": {"popular_ports": {"terms": {"field":"port"} } } }'
对port字段做聚合,结果名称为popular_ports。size设为0表示不关心搜索结果,结果的hits部分会是空值。
计算每种颜色车辆价格的平均值
GET /cars/transactions/_search { "size" : 0, "aggs": { "colors": { "terms": { "field": "color" }, "aggs": { "avg_price": { "avg": { "field": "price" } } } } } }
嵌套桶
每个颜色的汽车制造商的分布
GET /cars/transactions/_search { "size" : 0, "aggs": { "colors": { "terms": { "field": "color" }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make": { "terms": { "field": "make" } } } } } }
每个颜色的汽车制造商的分布,以及各个制造商生产汽车的最高和最低价格。
GET /cars/transactions/_search { "size" : 0, "aggs": { "colors": { "terms": { "field": "color" }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make" : { "terms" : { "field" : "make" }, "aggs" : { "min_price" : { "min": { "field": "price"} }, "max_price" : { "max": { "field": "price"} } } } } } } }
条形图
histogram
GET /cars/transactions/_search { "size" : 0, "aggs":{ "price":{ "histogram":{ "field": "price", "interval": 20000 }, "aggs":{ "revenue": { "sum": { "field" : "price" } } } } } }
terms桶 extended_stats度量
GET /cars/transactions/_search { "size" : 0, "aggs": { "makes": { "terms": { "field": "make", "size": 10 }, "aggs": { "stats": { "extended_stats": { "field": "price" } } } } } }