Skip to content
章节导航

Query DSL 桶聚合 Range 介绍和案例

分桶聚合查询 - Range

将字段的值划分为不同的范围,并将每个范围内的文档分配给相应的桶,对这些范围进行各种操作和计算。

语法介绍

shell
GET /index/_search
{
  "size": 0,
  "aggs": {
    "range_name": {
      "range": {
        "field": "field_name",
        "ranges": [
          { "key": "range_key_1", "from": from_value_1, "to": to_value_1 },
          { "key": "range_key_2", "from": from_value_2, "to": to_value_2 },
          ...
        ]
      },
      "aggs": {
        "sub_aggregation": {
          "sub_aggregation_type": {}
        }
      }
    }
  }
}

# 解析
# index:替换为要执行聚合查询的索引名称。
# range_name:替换为自定义的 range 聚合名称。
# field_name:替换为要聚合的字段名。
# ranges:指定范围数组,每个范围使用 key、from 和 to 参数进行定义。
# key:范围的唯一标识符。
# from:范围的起始值(包含)。
# to:范围的结束值(不包含)。
# sub_aggregation:指定在每个范围内进行的子聚合操作。
# sub_aggregation_type:替换单独子聚合操作的类型,可以是任何有效的子聚合类型。

数据准备

一个在线商店的商品索引,包括商品名称和价格字段

shell
POST /product_v4/_bulk
{ "index": {} }
{ "product_name": "飞驰人生3", "price" : 2000 }
{ "index": {} }
{ "product_name": "惊蛰无声", "price" : 200 }
{ "index": {} }
{ "product_name": "镖人:风起大漠", "price" : 300 }
{ "index": {} }
{ "product_name": "熊出没·年年有熊", "price" : 1500 }
{ "index": {} }
{ "product_name": "熊猫计划之部落奇遇记", "price" : 4120 }
{ "index": {} }
{ "product_name": "星河入梦", "price" : 180 }
{ "index": {} }
{ "product_name": "哪吒之魔童闹海", "price" : 250 }
{ "index": {} }
{ "product_name": "海洋奇缘2", "price" : 4770 }
{ "index": {} }
{ "product_name": "射雕英雄传:侠之大者", "price" : 400 }
{ "index": {} }
{ "product_name": "熊出没·重启未来", "price" : 150 }

案例说明

使用 range 聚合查询将商品按价格范围进行分桶,并计算每个分桶内的商品数量。如果没写key,则会默认生成

shell
GET /product_v4/_search
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 100 },
          { "from": 100, "to": 200 },
          { "from": 200 }
        ]
      }
    }
  }
}