23.1 聚合的引入
SELECT COUNT(color)
FROM table
GROUP BY color
- ElasticSearch中桶在概念上类似于 SQL 的分组(
GROUP BY ),而指标则类似于COUNT() 、SUM()、MAX()等统计方法
- 进而引入了两个概念:
- 桶(Buckets) 满足特定条件的文档的集合
- 指标(Metrics)对桶内的文档进行统计计算
- ElasticSearch包含3种聚合(Aggregation)方式
- 桶聚合(Bucket Aggregration)
- 指标聚合(Metric Aggregration)
- 管道聚合(Pipline Aggregration)
- 指标聚合和桶聚合很多情况下是组合在一起使用的,桶聚合本质上是一种特殊的指标聚合,它的聚合指标就是数据的条数count
23.2 准备数据
- 将会创建一些对汽车经销商有用的聚合,数据是关于汽车交易的信息:车型、制造商、售价、何时被出售等
POST /test-agg-cars/_bulk
{ "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" }
23.3 标准的聚合
- 汽车经销商可能会想知道哪个颜色的汽车销量最好,用聚合可以轻易得到结果,用terms 桶操作:
GET /test-agg-cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color.keyword"
}
}
}
}
23.4 多个聚合
GET /test-agg-cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color.keyword"
}
},
"make_by" : {
"terms" : {
"field" : "make.keyword"
}
}
}
}
23.5 聚合的嵌套
- 这个新的聚合层可以将 avg 度量嵌套置于 terms 桶内
GET /test-agg-cars/_search
{
"size" : 0,
"aggs": {
"colors": {
"terms": {
"field": "color.keyword"
},
"aggs": {
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
23.6 按分类学习Bucket聚合
- 前置条件的过滤:filter
- 在当前文档集上下文中定义与指定过滤器(Filter)匹配的所有文档的单个存储桶
GET /test-agg-cars/_search
{
"size": 0,
"aggs": {
"make_by": {
"filter": { "term": { "type": "honda" } },
"aggs": {
"avg_price": { "avg": { "field": "price" } }
}
}
}
}
大数据视频推荐: CSDN 大数据语音推荐: ELK7 stack开发运维 企业级大数据技术应用 大数据机器学习案例之推荐系统 自然语言处理 大数据基础 人工智能:深度学习入门到精通
|