查询结果缓存
TiDB Cloud Lake 在启用后会缓存并持久化每个已执行查询的结果。这可以显著缩短获得查询结果所需的时间。
缓存使用条件
只有在所有条件都满足时,查询结果才会从缓存中复用:
快速开始
在你的会话中启用查询结果缓存:
-- Enable query result cache
SET enable_query_result_cache = 1;
-- Optional: Cache all queries (including fast ones)
SET query_result_cache_min_execute_secs = 0;
配置项
性能示例
本示例演示如何缓存一个 TPC-H Q1 查询:
1. 启用缓存
SET enable_query_result_cache = 1;
SET query_result_cache_min_execute_secs = 0;
2. 第一次执行(无缓存)
SELECT
l_returnflag,
l_linestatus,
sum(l_quantity) as sum_qty,
sum(l_extendedprice) as sum_base_price,
sum(l_extendedprice * (1 - l_discount)) as sum_disc_price,
sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) as sum_charge,
avg(l_quantity) as avg_qty,
avg(l_extendedprice) as avg_price,
avg(l_discount) as avg_disc,
count(*) as count_order
FROM lineitem
WHERE l_shipdate <= add_days(to_date('1998-12-01'), -90)
GROUP BY l_returnflag, l_linestatus
ORDER BY l_returnflag, l_linestatus;
结果:4 行,耗时 21.492 秒(处理了 6 亿行)
3. 验证缓存条目
SELECT sql, query_id, result_size, num_rows FROM system.query_cache;
4. 第二次执行(来自缓存)
再次运行相同的查询。
结果:4 行,耗时 0.164 秒(处理了 0 行)
缓存管理
监控缓存使用情况
SELECT * FROM system.query_cache;
访问缓存结果
SELECT * FROM RESULT_SCAN(LAST_QUERY_ID());
缓存生命周期
在以下情况下,缓存结果会被自动移除:
- TTL 过期(默认:5 分钟)
- 结果大小超过限制(默认:1MB)
- 会话结束(缓存的作用域为会话)
- 底层数据发生变化(为保证一致性会自动失效)
- 表结构发生变化(schema 修改会使缓存失效)