语法:spop key [count] 示例:
127.0.0.1:6379> smembers myset
1) "v1"
2) "v2"
127.0.0.1:6379> spop myset 1
1) "v2"
127.0.0.1:6379> smembers myset
1) "v1"
语法:srandmember key [count] 示例:
127.0.0.1:6379> srandmember myset 2
1) "v4"
2) "v2"
语法:sinter key [key …] 示例:
127.0.0.1:6379> smembers myset
1) "v1"
2) "v3"
3) "v2"
127.0.0.1:6379> smembers myset2
1) "v1"
2) "v8"
127.0.0.1:6379> sinter myset myset2
1) "v1"
语法:sinterstore destination key [key …] 示例:
127.0.0.1:6379> smembers myset
1) "v1"
2) "v3"
3) "v2"
127.0.0.1:6379> smembers myset2
1) "v1"
2) "v8"
127.0.0.1:6379> sinterstore myset3 myset myset2
(integer) 1
127.0.0.1:6379> smembers myset3
1) "v1"
命令解析:从以上代码可以看出,我们把集合 myset 和 集合 myset2 的合集元素 v1 复制到了新的集合 myset3 中,但 v1 并不会从原有集合中移除。
语法:sunion key [key …] 示例:
127.0.0.1:6379> smembers group1
1) "java"
127.0.0.1:6379> smembers group2
1) "golang"
127.0.0.1:6379> sunion group1 group2
1) "java"
2) "golang"
语法:sunionstore destination key [key …] 示例:
127.0.0.1:6379> smembers group1
1) "java"
127.0.0.1:6379> smembers group2
1) "golang"
127.0.0.1:6379> sunionstore group3 group1 group2
(integer) 2
127.0.0.1:6379> smembers group3
1) "java"
2) "golang"
注意:只是把一个或多个集合的并集复制到新集合中,并不会在原集合中删除复制的元素。
语法:sdiff key [key …] 示例:
127.0.0.1:6379> smembers group1
1) "java"
2) "golang"
127.0.0.1:6379> smembers group2
1) "golang"
127.0.0.1:6379> sdiff group1 group2
1) "java"
注意:执行命令时集合的先后顺序会影响返回的结果,如下所示:
127.0.0.1:6379> sdiff group1 group2
1) "java"
127.0.0.1:6379> sdiff group2 group1
(empty list or set)
这是因为查询错集是以第一个集合为主的,当第二个元素包含第一个元素时,查询的错集结果就是空。
语法:sdiffstore destination key [key …] 示例:
127.0.0.1:6379> smembers group1
1) "java"
2) "golang"
127.0.0.1:6379> smembers group2
1) "golang"
127.0.0.1:6379> sdiffstore group3 group1 group2
(integer) 1
127.0.0.1:6379> smembers group3
1) "java"