redis_scan 用于按通配符搜索 redis 中的 key, 底层基于 SCAN 游标, 不会阻塞 redis.
redis_scan 与 redis_scan_type 同源: 前者按需返回 type / ttl(select 中写了才查), 后者固定返回这两列.
等效 DQL
- 虚拟表 SQL
-- 只取 key
select * from redis_scan where key = 'user:*' limit 100
-- 顺带取类型和过期时间(按需, 写哪列查哪列)
select key, type, ttl from redis_scan where key = 'user:*' limit 20
-- 等价写法: redis_scan_type 固定返回 key, type, ttl
select * from redis_scan_type where key = 'user:*' limit 20
即 redis_scan_type 等价于 select key, type, ttl from redis_scan.
- 等效 redis 原生命令
SCAN 0 MATCH user:* COUNT 100
TYPE <匹配到的 key>
TTL <匹配到的 key>
只有 select 中包含 type / ttl(或使用 redis_scan_type)时, 才会对每个 key 额外执行 TYPE / TTL.
返回字段
| 字段 | 类型 | 说明 |
|---|---|---|
| key | string | 匹配到的 key |
| type | string | 数据类型: string/hash/list/set/zset; 按需返回 |
| ttl | long | -1 永久, -2 不存在, 正数为剩余秒数; 按需返回 |
精确 key(不含 * / ?)直接走 TYPE + TTL, 不触发全库扫描; key 不存在时该行被跳过.
可查指标
| 指标 | 获取方式 | 说明 |
|---|---|---|
| 匹配的 key | where key = 'user:*' |
支持 * / ? 通配符 |
| key 的类型 | select key, type ... |
判断该用哪张虚拟表读写 |
| key 的过期时间 | select key, ttl ... |
-1 永久, -2 不存在 |
| 各类型分布 | 按 type 分组 | 统计每种数据结构各有多少 key |
| 即将过期数量 | 按 ttl 区间过滤 | ttl 为正数的 key 数量 |
| 匹配数量 | 对结果行 count | 受 limit 限制 |
查询示例
-- 搜索 key
select * from redis_scan where key = 'user:*' limit 100
-- 分页
select * from redis_scan where key = 'user:*' skip 100 limit 100
-- 顺带取类型和过期时间
select key, type, ttl from redis_scan where key = 'user:*' limit 20
-- 精确 key 查类型(不扫全库)
select * from redis_scan_type where key = 'k1'
-- 批量看类型
select * from redis_scan_type where key in ('k1', 'k2')
限制
- 必须带 where key 条件,
*/?为通配符; 不带 type/ttl 时默认 limit 100, 带 type/ttl(scan_type)时默认 limit 20. - 是(与 redis_randomkey 并列)支持 skip / limit 的虚拟表.
- 每个 key 查 type/ttl 都要额外执行一次 TYPE + TTL, key 多时耗时随数量线性增长; 只需要 key 列表时不要 select 这两列.
- 不支持 group by / order by(请在外层 SQL 中完成).
相关文档: redis_randomkey / redis-dao