集合类似 Java 中的 HashSet,内部实现是一个 value 永远为 null 的 HashMap,实际就是通过计算hash的方式来快速排重的,这也是 set 能提供判断一个成员是否在集合内的原因。
redis 的 sets 类型是使用哈希表构造的,因此复杂度是 o(1),它支持集合内的增删改查,并且支持多个集合间的交集、并集、差集操作。可以利用这些集合操作,解决程序开发过程当中很多数据集合间的问题。比如计算网站独立ip,用户画像中的用户标签,共同好友等功能
SADD key member [member ...]
# SADD key member [member ...]
> SADD testsets zhangsan lisi wangwu zhaoliu zhangsan
(integer) 4
> sadd testsets1 chendasheng zhansi liwu wangliu
(integer) 4
SCARD key
集合的数量。 当集合 key 不存在时,返回 0 。
> SCARD testsets
(integer) 4
SMEMBERS key
> SMEMBERS testsets
1) "zhaoliu"
2) "wangwu"
3) "lisi"
4) "zhangsan"
> SMEMBERS testsets1
1) "wangliu"
2) "liwu"
3) "zhansi"
4) "chendasheng"
SISMEMBER key member
存在返回 1
不存在返回 0
> SISMEMBER testsets chendasheng
(integer) 0
> SISMEMBER testsets1 chendasheng
(integer) 1
SDIFF key [key ...]
> SADD test1 1 2 3
> SADD test2 2 3 4
> SDIFF test1 test3
1) "1"
2) "2"
# destination 储存的集合
SDIFFSTORE destination key [key ...]
> SDIFFSTORE test4 test1 test3
(integer) 2
> SMEMBERS test4
1) "1"
2) "2"
SINTER key [key ...]
> SINTER test1 test2
1) "2"
2) "3"
# destination 储存的集合
SINTERSTORE destination key [key ...]
> SINTERSTORE test5 test1 test4
(integer) 2
> SMEMBERS test5
1) "1"
2) "2"
SUNION key [key ...]
> SADD test1 1 2 3
> SADD test2 2 3 4
> SUNION test1 test2
1) "1"
2) "2"
3) "3"
4) "4"
# destination 储存的集合
SUNIONSTORE destination key [key ...]
> SUNIONSTORE test6 test1 test2
(integer) 4
> SMEMBERS test6
1) "1"
2) "2"
3) "3"
4) "4"
SRANDMEMBER key [count]
> SMEMBERS test6
1) "1"
2) "2"
3) "3"
4) "4"
SPOP key [count]
> SPOP test6 2
1) "2"
2) "1"
> SMEMBERS test6
1) "3"
2) "4"
SREM key member [member ...]
> SREM test6 3 4
(integer) 2
> SMEMBERS test6
(empty array)
SMOVE source destination member
> SMOVE test1 test2 1
(integer) 1
> SMEMBERS test1
1) "2"
2) "3"
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
参考字符串迭代