*Redis SUNIONSTORE 命令
计算多个 Set 的并集,并将结果存入 destination Set。
*语法
SUNIONSTORE destination key [key ...]
*参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| destination | String | 是 | 结果 Set 的键名 |
| key | String | 是 | 一个或多个源 Set 键名 |
*返回值
| 条件 | 返回值 |
|---|---|
| 计算完成 | 结果 Set 的成员数量(Integer) |
*时间复杂度
O(N),N 为所有源 Set 成员总数。
*示例
> SADD set1 a b c
> SADD set2 b c d
> SUNIONSTORE result set1 set2
(integer) 4
> SMEMBERS result
1) "a"
2) "b"
3) "c"
4) "d"
*常见错误
| 错误 | 原因 | 解决 |
|---|---|---|
| ERR wrong number of arguments | 缺少 destination 或源 key | 检查参数是否完整 |
| WRONGTYPE Operation | 源 key 不是 Set 类型 | 确认所有源 key 均为 Set 类型 |
| 覆盖重要数据 | destination 与已有 key 同名 | 使用临时键名或确认覆盖意图 |
*最佳实践
- 大数据量集合运算:用 SUNIONSTORE 替代 SUNION,避免返回大数组阻塞网络。
临时结果:结果存入新 key,处理完后删除,避免长期占用内存。
TTL 管理:为 destination 设置过期时间,避免临时结果长期占用内存。
分批处理:源 Set 数量过多时,分批执行并合并结果,减少单次计算压力。
*5. 键名规范:destination 使用明确前缀标识为临时/计算结果,如 tmp:sunion:result。
*FAQ
Q1: SUNIONSTORE 会覆盖 destination 吗? A: 会。destination 已存在则被覆盖。
Q2: destination 可以是源 Set 之一吗? A: 可以。但结果会覆盖该 key。
Q3: SUNIONSTORE 和 SUNION 性能有差异吗? A: 计算逻辑相同,但 SUNIONSTORE 结果写入内存而非网络传输,大数据量时网络开销更小。
Q4: 源 Set 为空会怎样? A: 并集为空,destination 会被创建为空 Set(覆盖原有内容)。
Q5: 可以对非 Set 类型的 key 执行吗? A: 可以,Redis 会自动将非 Set 的空 key 视为空 Set 参与运算,但已有非 Set 类型的 key 会报错。