聚合索引
聚合索引通过预计算并存储聚合结果,显著加速分析型查询,避免在常见分析操作中扫描整张表。
它解决了什么问题?
大规模数据集上的分析型查询会面临显著的性能挑战:
示例:销售分析查询 SELECT SUM(revenue), COUNT(*) FROM sales WHERE region = 'US' 需要处理 1 亿行数据。没有聚合索引时,它需要扫描所有美国销售记录;有了聚合索引后,它可以立即返回预计算结果。
工作原理
- 创建索引 → 定义需要预计算的聚合查询
- 结果存储 → TiDB Cloud Lake 将聚合结果存储在优化后的数据块中
- 查询匹配 → 传入的查询会自动使用预计算结果
- 自动修改 → 当底层数据发生变化时,结果会刷新
快速开始
-- Create table with sample data
CREATE TABLE sales(region VARCHAR, product VARCHAR, revenue DECIMAL, quantity INT);
-- Create aggregating index for common analytics
CREATE AGGREGATING INDEX sales_summary AS
SELECT region, SUM(revenue), COUNT(*), AVG(quantity)
FROM sales
GROUP BY region;
-- Refresh the index (manual mode)
REFRESH AGGREGATING INDEX sales_summary;
-- Verify the index is used
EXPLAIN SELECT region, SUM(revenue) FROM sales GROUP BY region;
支持的操作
刷新策略
自动刷新与手动刷新
-- Automatic refresh (updates with every data change)
CREATE AGGREGATING INDEX auto_summary AS
SELECT region, SUM(revenue) FROM sales GROUP BY region SYNC;
-- Manual refresh (update on demand)
CREATE AGGREGATING INDEX manual_summary AS
SELECT region, SUM(revenue) FROM sales GROUP BY region;
REFRESH AGGREGATING INDEX manual_summary;
性能示例
以下示例展示了显著的性能提升:
-- Prepare data
CREATE TABLE agg(a int, b int, c int);
INSERT INTO agg VALUES (1,1,4), (1,2,1), (1,2,4), (2,2,5);
-- Create an aggregating index
CREATE AGGREGATING INDEX my_agg_index AS SELECT MIN(a), MAX(c) FROM agg;
-- Refresh the aggregating index
REFRESH AGGREGATING INDEX my_agg_index;
-- Verify if the aggregating index works
EXPLAIN SELECT MIN(a), MAX(c) FROM agg;
-- Key indicators in the execution plan:
-- ├── aggregating index: [SELECT MIN(a), MAX(c) FROM default.agg]
-- ├── rewritten query: [selection: [index_col_0 (#0), index_col_1 (#1)]]
-- This shows the query uses precomputed results instead of scanning raw data
最佳实践
管理命令
重要说明
适合使用聚合索引的场景:
- 频繁的分析型查询(仪表盘、报表)
- 具有重复聚合的大规模数据集
- 稳定的查询模式
- 对性能要求高的应用
不适合使用的场景:
- 数据频繁变化
- 一次性的分析型查询
- 小表上的简单查询
配置
-- Enable/disable aggregating index feature
SET enable_aggregating_index_scan = 1; -- Enable (default)
SET enable_aggregating_index_scan = 0; -- Disable
聚合索引最适用于大规模数据集上的重复性分析负载。建议从最常用的仪表盘和报表查询开始。