
Elasticsearch 的聚合(Aggregations)功能强大,用于执行复杂的数据分析和统计操作。聚合可以帮助你从大量数据中提取有价值的见解。聚合主要分为以下几类:
矩阵聚合(Matrix Aggregations):处理和分析矩阵相关的数据。
计算字段的平均值。
GET /my_index/_search
{
"size": 0,
"aggs": {
"average_age": {
"avg": {
"field": "age"
}
}
}
}
计算字段的最大值。
GET /my_index/_search
{
"size": 0,
"aggs": {
"max_age": {
"max": {
"field": "age"
}
}
}
}
计算字段的最小值。
GET /my_index/_search
{
"size": 0,
"aggs": {
"min_age": {
"min": {
"field": "age"
}
}
}
}
计算字段的总和。
GET /my_index/_search
{
"size": 0,
"aggs": {
"total_age": {
"sum": {
"field": "age"
}
}
}
}
提供字段的基本统计信息,如最小值、最大值、平均值和总和。
GET /my_index/_search
{
"size": 0,
"aggs": {
"age_stats": {
"stats": {
"field": "age"
}
}
}
}
按字段值进行分组计数。
GET /my_index/_search
{
"size": 0,
"aggs": {
"age_groups": {
"terms": {
"field": "age"
}
}
}
}
按指定的数值范围进行分组。
GET /my_index/_search
{
"size": 0,
"aggs": {
"age_ranges": {
"range": {
"field": "age",
"ranges": [
{ "to": 20 },
{ "from": 20, "to": 30 },
{ "from": 30 }
]
}
}
}
}
按日期字段进行分组,间隔可以是年、月、日等。
GET /my_index/_search
{
"size": 0,
"aggs": {
"sales_over_time": {
"date_histogram": {
"field": "sale_date",
"calendar_interval": "month"
}
}
}
}
基于时间序列数据计算移动平均值。
GET /my_index/_search
{
"size": 0,
"aggs": {
"sales_over_time": {
"date_histogram": {
"field": "sale_date",
"calendar_interval": "month"
},
"aggs": {
"sales": {
"sum": {
"field": "sales_amount"
}
},
"moving_avg_sales": {
"moving_avg": {
"buckets_path": "sales"
}
}
}
}
}
}
计算多个数值字段的统计信息,如协方差、相关性等。
GET /my_index/_search
{
"size": 0,
"aggs": {
"matrix_stats": {
"matrix_stats": {
"fields": ["field1", "field2", "field3"]
}
}
}
}
一个复杂的查询示例,包含嵌套的桶聚合和度量聚合。
GET /my_index/_search
{
"size": 0,
"aggs": {
"by_gender": {
"terms": {
"field": "gender"
},
"aggs": {
"age_stats": {
"stats": {
"field": "age"
}
},
"age_ranges": {
"range": {
"field": "age",
"ranges": [
{ "to": 20 },
{ "from": 20, "to": 30 },
{ "from": 30 }
]
},
"aggs": {
"avg_income": {
"avg": {
"field": "income"
}
}
}
}
}
}
}
}
gender
字段分组。age
字段统计信息。age
字段进行范围分组。income
。通过这些聚合操作,Elasticsearch 能够执行复杂的数据分析,从而为用户提供有价值的洞察。