前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Elasticsearch aggs分类统计汇总

Elasticsearch aggs分类统计汇总

原创
作者头像
周银辉
发布2024-06-28 15:53:56
1150
发布2024-06-28 15:53:56
举报
文章被收录于专栏:ElasticSearch

案例一:

原始数据

代码语言:txt
复制
PUT cars 
POST _bulk
{"index":{"_index":"cars","_id":"1"}}
{"model":"A","color":"red"}
{"index":{"_index":"cars","_id":"2"}}
{"model":"A","color":"white"}
{"index":{"_index":"cars","_id":"3"}}
{"model":"A","color":"black"}
{"index":{"_index":"cars","_id":"4"}}
{"model":"A","color":"yellow"}
{"index":{"_index":"cars","_id":"5"}}
{"model":"B","color":"red"}
{"index":{"_index":"cars","_id":"6"}}
{"model":"B","color":"white"}
{"index":{"_index":"cars","_id":"7"}}
{"model":"C","color":"black"}
{"index":{"_index":"cars","_id":"8"}}
{"model":"C","color":"red"}
{"index":{"_index":"cars","_id":"9"}}
{"model":"C","color":"white"}
{"index":{"_index":"cars","_id":"10"}}
{"model":"C","color":"yellow"}
{"index":{"_index":"cars","_id":"11"}}
{"model":"C","color":"blue"}
{"index":{"_index":"cars","_id":"12"}}
{"model":"D","color":"red"}
{"index":{"_index":"cars","_id":"13"}}
{"model":"A","color":"red"}

实现mysql中的如下需求:

代码语言:txt
复制
SELECT model,COUNT(DISTINCT color) color_count 
FROM cars 
GROUP BY model 
HAVING color_count > 1 
ORDER BY color_count desc LIMIT 2;

mysql与ES的对应关系如下:

  1. Group By VS Terms/Metric Aggregation
  2. Having Condition VS Bucket Filter Aggregation
  3. Order By Limit VS Bucket Sort Aggregation
代码语言:txt
复制
GET cars/_search
{
  "size": 0,
  "aggs": {
    "aggmodels": {
      "terms": {
        "field": "model.keyword"
      },
      "aggs": {
        "color_count": {
          "cardinality": {
            "field": "color.keyword"
          }
        },
        "color_count_filter": {
          "bucket_selector": {
            "buckets_path": {
              "colorcount": "color_count"
            },
            "script": "params.colorcount>1"
          }
        },
        "color_count_sort": {
          "bucket_sort": {
            "sort": {
              "color_count": "desc"
            },
            "size": 2
          }
        }
      }
    }
  }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 案例一:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档