Query DSL 桶聚合 Terms 案例
什么桶bucket聚合
对数据集进行分组 group by,然后在组上进行指标聚合,在 ES 中称为分桶,桶聚合 bucketing
基本语法格式
shell
GET /index/_search
{
"size": 0,
"aggs": {
"aggregation_name": {
"bucket_type": {
"bucket_options": {
"bucket_option_name": "bucket_option_value",
...
},
"aggs": {
"sub_aggregation_name": {
"sub_aggregation_type": {
"sub_aggregation_options": {
"sub_aggregation_option_name": "sub_aggregation_option_value",
...
}
}
}
}
}
}
}
}
#解析
# index: 替换为要执行聚合查询的索引名称。
# aggregation_name: 替换为自定义的聚合名称。
# bucket_type: 替换为特定的桶聚合类型(如 terms、date_histogram、range 等)。
# bucket_option_name 和 bucket_option_value: 替换为特定桶聚合选项的名称和值。
# sub_aggregation_name: 替换为子聚合的名称。
# sub_aggregation_type: 替换为特定的子聚合类型(如 sum、avg、max、min 等)。
# sub_aggregation_option_name 和 sub_aggregation_option_value: 替换为特定子聚合选项的名称和值分桶聚合查询 - Terms 案例
创建索引库
数据准备:假设有一个在线书店的图书销售记录索引,包含图书名称和销售数量字段。
shell
PUT /book_sales
{
"mappings": {
"properties": {
"book_title": {
"type": "keyword"
},
"sales_count": {
"type": "integer"
}
}
},
"settings": {
"number_of_shards": 2,
"number_of_replicas": 0
}
}插入数据
shell
POST /book_sales/_bulk
{ "index": {} }
{ "book_title": "飞驰人生3", "sales_count" : 100 }
{ "index": {} }
{ "book_title": "惊蛰无声", "sales_count" : 50 }
{ "index": {} }
{ "book_title": "镖人:风起大漠", "sales_count" : 80 }
{ "index": {} }
{ "book_title": "熊出没·年年有熊", "sales_count" : 120 }
{ "index": {} }
{ "book_title": "熊猫计划之部落奇遇记", "sales_count" : 90 }
{ "index": {} }
{ "book_title": "星河入梦", "sales_count" : 70 }
{ "index": {} }
{ "book_title": "哪吒之魔童闹海", "sales_count" : 110 }
{ "index": {} }
{ "book_title": "海洋奇缘2", "sales_count" : 200 }
{ "index": {} }
{ "book_title": "射雕英雄传:侠之大者", "sales_count" : 150 }
{ "index": {} }
{ "book_title": "熊出没·重启未来", "sales_count" : 80 }查询
案例说明:使用 terms 聚合查询将图书按销售数量进行分桶,并获取每个分桶内的销售数量总和。
shell
GET /book_sales/_search
{
"size": 0,
"aggs": {
"book_buckets": {
"terms": {
"field": "book_title",
"size": 10
},
"aggs": {
"total_sales": {
"sum": {
"field": "sales_count"
}
}
}
}
}
}
朔风