Redis SUNIONSTORE命令

Redis SUNIONSTORE命令教程

Redis 的 SUNIONSTORE 命令类似于 SUNION 命令,用于计算集合的并集,但它将结果保存到 destination 集合,而不是简单地返回结果集。

如果 destination 已经存在,则将其覆盖。destination 可以是 key 本身。

Redis SUNIONSTORE命令详解

语法

192.168.98.70:6379> SUNIONSTORE destination key [key ...]

参数

参数 描述
destination 保存结果的目的集合。
KEY 要计算并集的集合的键。

返回值

结果集中的元素数量。

时间复杂度

O(N), N 是所有给定集合的成员数量之和。

可用版本

>= 1.0.0

案例

destination不存在

destination 不存在,并集被保存到 destination

192.168.98.70:6379> SADD haicoder Redis Mongo Mysql (integer) 3 192.168.98.70:6379> SADD hicoder SqlServer SQL Mongo (integer) 3 192.168.98.70:6379> SCARD coder (integer) 0 192.168.98.70:6379> SUNIONSTORE coder haicoder hicoder (integer) 5 192.168.98.70:6379> SMEMBERS coder 1) "Redis" 2) "Mongo" 3) "SQL" 4) "Mysql" 5) "SqlServer" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

我们首先,使用 SADD 命令,向键为 haicoder 的集合插入元素 Redis、Mongo 和 Mysql。使用 SADD 命令,向键为 hicoder 的集合插入元素 SqlServer、SQL 和 Mongo。

接着,我们使用 SCARD 命令,获取键为 coder 的集合的元素个数,返回 0,即集合不存在。使用 SUNIONSTORE 命令,将键为 haicoder 的集合与键为 hicoder 的集合的元素的并集,保存在集合 coder 中。

最后,我们使用 SMEMBERS 获取键为 coder 的集合的所有元素,返回了集合 haicoder 与集合 hicoder 的并集。

destination存在

destination 存在,destination 被清空后保存并集元素

192.168.98.70:6379> SADD haicoder Redis Mongo Mysql (integer) 3 192.168.98.70:6379> SADD hicoder SqlServer SQL Mongo (integer) 3 192.168.98.70:6379> SADD coder coder (integer) 1 192.168.98.70:6379> SUNIONSTORE coder haicoder hicoder (integer) 5 192.168.98.70:6379> SMEMBERS coder 1) "Redis" 2) "Mongo" 3) "SQL" 4) "Mysql" 5) "SqlServer" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

我们首先,使用 SADD 命令,向键为 haicoder 的集合插入元素 Redis、Mongo 和 Mysql。使用 SADD 命令,向键为 hicoder 的集合插入元素 SqlServer、SQL 和 Mongo。

接着,我们使用 SADD 命令,向键为 coder 的集合插入元素 coder。使用 SUNIONSTORE 命令,将键为 haicoder 的集合与键为 hicoder 的集合的元素的并集,保存在集合 coder 中。

最后,我们使用 SMEMBERS 获取键为 coder 的集合的所有元素,返回了集合 haicoder 与 集合 hicoder 的并集,同时原来 coder 集合中的元素已经不存在。

destination为非集合类型

destination 为非集合类型,destination 被清空后保存并集元素

192.168.98.70:6379> SADD haicoder Redis Mongo Mysql (integer) 3 192.168.98.70:6379> SADD hicoder SqlServer SQL Mongo (integer) 3 192.168.98.70:6379> LPUSH coder SQL (integer) 1 192.168.98.70:6379> SUNIONSTORE coder haicoder hicoder (integer) 5 192.168.98.70:6379> SMEMBERS coder 1) "Redis" 2) "Mongo" 3) "SQL" 4) "Mysql" 5) "SqlServer" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

我们首先,使用 SADD 命令,向键为 haicoder 的集合插入元素 Redis、Mongo 和 Mysql。使用 SADD 命令,向键为 hicoder 的集合插入元素 SqlServer、SQL 和 Mongo。

接着,我们使用 LPUSH 命令,向键为 coder 的列表中插入元素 SQL。

使用 SUNIONSTORE 命令,将键为 haicoder 的集合与键为 hicoder 的集合的元素的并集,保存在列表元素 coder 中,此时 coder 为列表类型,所以列表被清空,重新保存了并集元素。

最后,使用 SMEMBERS 获取键为 coder 的集合的所有元素,返回了集合 haicoder 与集合 hicoder 的并集。

Redis SUNIONSTORE命令总结

Redis 的 SUNIONSTORE 命令类似于 SUNION 命令,但它将结果保存到 destination 集合,而不是简单地返回结果集。Redis SUNIONSTORE 命令语法:

192.168.98.70:6379> SUNIONSTORE destination key [key ...]