(六)Redis数据类型之Set

sadd

sadd key member [member1 …]

给集合内新增成员,若集合不存在则创建集合并新增成员。

1
2
3
4
5
6
7
8
9
10
11
12
13
sadd set one
sadd set two
sadd set three
sadd set four
sadd set five


Docker:0>smembers set
1) "four"
2) "two"
3) "one"
4) "three"
5) "five"

srem

srem key member [member1 …]

移除元素

smove

smove source destination member

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Docker:0>sadd set1 dick joe nick joe
"3"

Docker:0>sadd set2 helen steve frank
"3"

Docker:0>smove set1 set2 joe
"1"

Docker:0>smembers set2
1) "steve"
2) "joe"
3) "frank"
4) "helen"

Docker:0>smembers set1
1) "nick"
2) "dick"

smembers

smembers key

查看成员

1
2
3
4
5
Docker:0>smembers set2
1) "steve"
2) "joe"
3) "frank"
4) "helen"

scard

scard key

返回集合中成员的个数

1
2
3
4
5
 Docker:0>scard set2
"4"

Docker:0>scard set1
"2"

srandmember

srandmember key [count]

从集合中随机返回指定个数的成员

1
2
3
Docker:0>srandmember set2 2
1) "helen"
2) "frank"

sismember

sismember key member

判断是否存在于指定key的集合中

1
2
3
4
5
 Docker:0>smembers set1
1) "nick"
2) "dick"
Docker:0>sismember set1 dick
"1"

spop

spop key

从集合中随机弹出一个成员,返回该成员并从集合中删除该成员

1
2
3
4
5
6
7
8
9
10
11
Docker:0>smembers set2
1) "steve"
2) "joe"
3) "frank"
4) "helen"
Docker:0>spop set2
"joe"
Docker:0>smembers set2
1) "steve"
2) "frank"
3) "helen"

sinter

sinter key [key2 key3 …]

取多个集合的交集,返回这些集合中共同拥有的成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Docker:0>smembers setA
1) "C"
2) "A"
3) "F"
4) "B"
5) "D"
6) "E"
Docker:0>smembers setB
1) "E"
2) "D"
3) "B"
4) "C"
5) "F"
Docker:0>smembers setC
1) "D"
2) "C"

Docker:0>sinter setA setB setC
1) "D"
2) "C"

sinterstore

sinterstore destination key [key1 key2 …]

取多个集合的交集∩, 结果存于新的set

1
2
3
4
5
6
Docker:0>sinterstore rest_A_B_C setA setB setC
"2"

Docker:0>smembers rest_A_B_C
1) "D"
2) "C"

sunion

sunion key [key1 key2 …]

求并集∪,相同的成员会被去重

1
2
3
4
5
6
7
Docker:0>sunion setA setB setC
1) "F"
2) "B"
3) "D"
4) "A"
5) "C"
6) "E"

sunionstore

sunionstore destination key [key …]

将多个集合的并集的结果保存为一个新的集合destination ,返回新集合的成员个数。

1
2
3
4
5
6
7
8
9
10
Docker:0>sunionstore union_A_B_C setA setB setC
"6"

Docker:0>smembers union_A_B_C
1) "F"
2) "B"
3) "D"
4) "A"
5) "C"
6) "E"

sdiff

sdiff key [key1 key2 …]

取多个集合的差集,以最左边的为主集合,返回左集合中有而其他集合没有的成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Docker:0>smembers setA
1) "C"
2) "A"
3) "F"
4) "B"
5) "D"
6) "E"
Docker:0>smembers setB
1) "E"
2) "D"
3) "B"
4) "C"
5) "F"
Docker:0>smembers setC
1) "D"
2) "C"
※ 集合A 比集合B和集合C多了A这个元素
Docker:0>sdiff setA setB setC
1) "A"

sdiffstore

sdiffstore destination key [key1 key2 …]

将多个集合的差集的结果保存为一个新的集合destination,返回新集合的成员个数

1
2
3
4
5
6

Docker:0>sdiffstore diff_A_B_C setA setB setC
"1"

Docker:0>smembers diff_A_B_C
1) "A"

set 集合结合具体业务场景:

应用场景

  • 抽奖:随机返回指定个数成员
  • 共同好友:取交集
  • 好友推荐:根据标签取交集,交集的成员个数大于某个阈值触发推荐动作