温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

elasticsearch聚合分析怎么用

发布时间:2026-09-16 19:02:29 来源:亿速云 阅读:103 作者:小樊 栏目:软件技术

Elasticsearch 的聚合(Aggregation)用于在搜索结果上做“分组、统计、分析”,类似 SQL 里的 GROUP BY + 聚合函数。下面从概念 → 常用类型 → 示例 → 使用方式逐步说明。


一、聚合的基本概念

聚合通常写在查询的 aggs 字段中:

GET /index_name/_search
{
  "size": 0,
  "aggs": {
    "聚合名称": {
      "聚合类型": { ... }
    }
  }
}
  • size: 0:只看聚合结果,不看原始文档
  • aggs:聚合定义
  • 聚合可以嵌套

二、常见聚合类型

1️⃣ 指标聚合(Metrics Aggregations)

对数值做统计

类型 说明
avg 平均值
sum 求和
min / max 最小 / 最大
value_count 数量
stats 一次性统计
cardinality 去重计数

示例:求平均年龄

{
  "aggs": {
    "avg_age": {
      "avg": { "field": "age" }
    }
  }
}

2️⃣ 桶聚合(Bucket Aggregations)

按条件分组(类似 GROUP BY)

✅ terms(按字段分组)

{
  "aggs": {
    "by_city": {
      "terms": { "field": "city" }
    }
  }
}

✅ date_histogram(按时间分组)

{
  "aggs": {
    "by_day": {
      "date_histogram": {
        "field": "create_time",
        "calendar_interval": "day"
      }
    }
  }
}

✅ range(数值区间)

{
  "aggs": {
    "age_range": {
      "range": {
        "field": "age",
        "ranges": [
          { "to": 18 },
          { "from": 18, "to": 30 },
          { "from": 30 }
        ]
      }
    }
  }
}

3️⃣ 嵌套聚合(非常常用)

示例:每个城市的平均年龄

{
  "aggs": {
    "by_city": {
      "terms": { "field": "city" },
      "aggs": {
        "avg_age": {
          "avg": { "field": "age" }
        }
      }
    }
  }
}

三、完整示例

索引示例数据

{ "name": "Tom", "city": "Beijing", "age": 25 }
{ "name": "Lucy", "city": "Shanghai", "age": 30 }
{ "name": "Jack", "city": "Beijing", "age": 35 }

查询:各城市人数 + 平均年龄

GET /user/_search
{
  "size": 0,
  "aggs": {
    "by_city": {
      "terms": { "field": "city" },
      "aggs": {
        "avg_age": { "avg": { "field": "age" } }
      }
    }
  }
}

四、在代码里怎么用?

Java(High Level Client)

SearchSourceBuilder source = new SearchSourceBuilder();
TermsAggregationBuilder agg =
    AggregationBuilders.terms("by_city").field("city");
agg.subAggregation(AggregationBuilders.avg("avg_age").field("age"));

source.aggregation(agg);

五、常见坑

❗ text 字段不能直接聚合
✅ 用 keyword:

"city.keyword"

❗ 聚合字段要建索引
❗ 数据量大时注意 size 和性能


六、你可以告诉我

  • 使用的 ES 版本
  • 是 SQL / DSL / Java / Python
  • 想做的 具体业务场景

我可以直接帮你写聚合语句。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手