狂自私

导航

ES聚合有哪些方式

Elasticsearch 提供了多种聚合(Aggregation)方式,允许用户对数据进行分析和统计。聚合可以分为几类,包括桶聚合(Bucket Aggregations)、度量聚合(Metric Aggregations)等。以下是一些常见的聚合方式及其示例:

1. 桶聚合(Bucket Aggregations)

桶聚合用于将文档分组,并可以在每个组上执行其他聚合。

a. Terms Aggregation

terms 聚合用于按字段值将文档分组,例如统计各个类别的文档数量。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": {
        "field": "category.keyword"
      }
    }
  }
}
  • 解释:这个查询将返回 category 字段中每个不同值的文档数量。

b. Date Histogram Aggregation

date_histogram 聚合用于按时间段对文档进行分组,例如按天、月、年统计。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "daily_sales": {
      "date_histogram": {
        "field": "sale_date",
        "interval": "day"
      }
    }
  }
}
  • 解释:这个查询将返回按天分组的销售数量。

2. 度量聚合(Metric Aggregations)

度量聚合用于对数值字段执行计算,例如求和、平均值、最大值等。

a. Sum Aggregation

sum 聚合用于计算一个字段的总和。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "total_sales": {
      "sum": {
        "field": "sales_amount"
      }
    }
  }
}
  • 解释:这个查询将返回 sales_amount 字段的总和。

b. Average Aggregation

avg 聚合用于计算一个字段的平均值。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}
  • 解释:这个查询将返回 price 字段的平均值。

3. 复合聚合(Composite Aggregation)

复合聚合允许按照多个维度对文档进行分组和聚合,非常适合需要分页的聚合。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "composite_agg": {
      "composite": {
        "sources": [
          {
            "category": {
              "terms": {
                "field": "category.keyword"
              }
            }
          },
          {
            "price_range": {
              "range": {
                "field": "price",
                "ranges": [
                  { "to": 50 },
                  { "from": 50, "to": 100 },
                  { "from": 100 }
                ]
              }
            }
          }
        ]
      }
    }
  }
}
  • 解释:这个查询将根据 categoryprice 的范围对文档进行分组。

4. 嵌套聚合(Nested Aggregations)

嵌套聚合允许在一个聚合的结果上进行进一步的聚合。例如,可以在 terms 聚合内进行 avg 聚合。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": {
        "field": "category.keyword"
      },
      "aggs": {
        "average_price": {
          "avg": {
            "field": "price"
          }
        }
      }
    }
  }
}
  • 解释:这个查询将返回每个类别的文档数量及其对应的平均价格。

5. 过滤聚合(Filter Aggregation)

过滤聚合用于在特定条件下对文档进行聚合。

示例:

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "filtered_sales": {
      "filter": {
        "term": {
          "category.keyword": "electronics"
        }
      },
      "aggs": {
        "total_sales": {
          "sum": {
            "field": "sales_amount"
          }
        }
      }
    }
  }
}
  • 解释:这个查询将只计算 category 为 "electronics" 的文档的销售总和。

总结

Elasticsearch 提供了丰富的聚合功能,支持各种复杂的数据分析需求。通过使用不同类型的聚合,你可以从数据中提取有价值的信息,帮助做出更好的决策。在实际应用中,可以根据需求组合使用这些聚合方式,满足各种数据分析场景。

posted on 2024-09-12 08:29  狂自私  阅读(278)  评论(0)    收藏  举报