Redis 集合(Set)

Set 是无序去重集合,做标签、共同好友、抽奖。

Beginner
Key PointsSet 自动去重,交集/并集/差集是 O(1) 级集合运算的利器。

基础操作

Shell
SADD tags:1 "go" "redis" "db"
SADD tags:2 "redis" "mysql"
SMEMBERS tags:1          # 全部成员
SISMEMBER tags:1 "go"    # 是否包含
SCARD tags:1             # 成员数
Output
(integer) 3
1) "go"
2) "redis"
3) "db"
(integer) 2

集合运算

Shell
SINTER tags:1 tags:2     # 交集:共同兴趣
SUNION tags:1 tags:2     # 并集
SDIFF tags:1 tags:2      # 差集:tags:1 有而 tags:2 没有
SPOP tags:1             # 随机弹出一个(抽奖)
Output
1) "redis"
1) "go"
2) "redis"
3) "db"
1) "go"
2) "db"
Mutual friends, interest intersection and dedupe counts all fit Set. For a draw use SRANDMEMBER (no removal) or SPOP (removes, guarantees no repeat winner).

Friends & Partners