23.Elasticsearch索引聚合查询—Bucket聚合-1

23.1 聚合的引入

  • 在SQL结果中常有:
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 多个聚合

  • 同时计算两种桶的结果:对color和对make
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开发运维
企业级大数据技术应用
大数据机器学习案例之推荐系统
自然语言处理
大数据基础
人工智能:深度学习入门到精通

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值