set

命令

  • SADD:
  • SMEMBERS:
  • SREM:
  • SCARD:
  • SISMEMBER:
  • SRANDMEMBER:
  • SPOP:
  • SINTER:
  • SUNION:
  • SDIFF:
  • SINTERSTORE:
  • SUNIONSTORE:
  • SDIFFSTORE:

示例

创建集合键

127.0.0.1:6379> SADD myset2 1 2 3 4 5
(integer) 5

获取集合键中的元素

127.0.0.1:6379> SMEMBERS myset2
1) "1"
2) "2"
3) "3"
4) "4"
5) "5"

删除集合键中指定元素

127.0.0.1:6379> SREM myset2 5
(integer) 1
127.0.0.1:6379> SMEMBERS myset2
1) "1"
2) "2"
3) "3"
4) "4"

随即删除集合键中一个元素

127.0.0.1:6379> SPOP myset2
"1"
127.0.0.1:6379> SPOP myset2
"4"
127.0.0.1:6379> SPOP myset2
"2"
127.0.0.1:6379> SPOP myset2
"3"

获取集合键的元素个数

127.0.0.1:6379> SADD myset2 1 2 3 4
(integer) 4
127.0.0.1:6379> SCARD myset2
(integer) 4

判断集合键中是否存在特定值的元素

127.0.0.1:6379> SISMEMBER myset2 4
(integer) 1
127.0.0.1:6379> SISMEMBER myset2 5
(integer) 0

随机返回集合键中指定数量的元素

127.0.0.1:6379> SRANDMEMBER myset2
"1"
127.0.0.1:6379> SRANDMEMBER myset2 2
1) "1"
2) "4"

获取多个集合键的交集元素

127.0.0.1:6379> SADD myset1 Music Game Sport
(integer) 3
127.0.0.1:6379> SADD myset2 Music Coding
(integer) 2
127.0.0.1:6379> SADD myset3 Music Writing
(integer) 2
127.0.0.1:6379> SINTER myset1 myset2 
1) "Music"
127.0.0.1:6379> SINTER myset1 myset2 myset3
1) "Music"

获取多个集合键中元素的并集

127.0.0.1:6379> SUNION myset1 myset2 myset3
1) "Music"
2) "Writing"
3) "Coding"
4) "Sport"
5) "Game"

获取多个集合键中元素的差集

PS: 位置不同得到的结果不同

127.0.0.1:6379> SDIFF myset1 myset2 myset3
1) "Game"
2) "Sport"

由于Redis进行交集、并集、差集计算相对来说比较耗费性能,所以建议将元素过多且通用的结果保存起来,以避免不必要的性能开销

保存多个集合键的交集

127.0.0.1:6379> SINTERSTORE myset_1_2_3_inter myset1 myset2 myset3
(integer) 1
127.0.0.1:6379> SMEMBERS myset_1_2_3_inter
1) "Music"

保存多个集合键的并集

127.0.0.1:6379> SUNIONSTORE myset_1_2_3_union myset1 myset2 myset3
(integer) 5
127.0.0.1:6379> SMEMBERS myset_1_2_3_union
1) "Music"
2) "Writing"
3) "Coding"
4) "Sport"
5) "Game"

保存多个集合键的差集

127.0.0.1:6379> SDIFFSTORE myset_1_2_3_diff myset1 myset2 myset3
(integer) 2
127.0.0.1:6379> SMEMBERS myset_1_2_3_diff
1) "Game"
2) "Sport"

内部编码

  • intset: 当集合键内元素都是整数,并且元素个数小于set-max-intset-entries(默认512)时,会使用intset作为内部编码
  • hashtable: 当集合键元素不满足intset条件时,会使用hashtable作为内部编码

应用场景

标签

琢磨下网易云音乐里面的细节

  • 用户添加标签
  • 标签添加用户

results matching ""

    No results matching ""