Redis SINTERSTORE命令

Redis SINTERSTORE命令教程

Redis 的 SINTERSTORE 命令类似于 SINTER 命令,用于返回 集合 的交集,但它将结果保存到 destination 集合,而不是简单地返回结果集。如果 destination 集合已经存在,则将其覆盖。

destination 可以是 KEY 本身。

Redis SINTERSTORE命令详解

语法

192.168.98.70:6379> SINTERSTORE destination KEY [KEY ...]

参数

参数 描述
destination 要将返回的交集的结果保存到的目的集合。
KEY 要返回交集的集合的键。

返回值

结果集中的成员数量。

时间复杂度

O(N * M), N 为给定集合当中基数最小的集合, M 为给定集合的个数。

可用版本

>= 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> SINTERSTORE coder haicoder hicoder (integer) 1 192.168.98.70:6379> SMEMBERS coder 1) "Mongo" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

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

接着,我们使用 SCARD 命令,获取键为 coder 的集合的元素个数,返回 0,即集合不存在。使用 SINTERSTORE 命令,将键为 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> SINTERSTORE coder haicoder hicoder (integer) 1 192.168.98.70:6379> SMEMBERS coder 1) "Mongo" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

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

接着,我们使用 SADD 命令,向键为 coder 的集合插入元素 coder。使用 SINTERSTORE 命令,将键为 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> SINTERSTORE coder haicoder hicoder (integer) 1 192.168.98.70:6379> SMEMBERS coder 1) "Mongo" 192.168.98.70:6379> DEL haicoder hicoder coder (integer) 3

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

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

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

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

Redis SINTERSTORE命令总结

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

192.168.98.70:6379> SINTERSTORE destination KEY [KEY ...]