Redis - 集合

2020/01/27

常用命令

集合内

  • 增删查
# 1. sadd key element [element ...]
127.0.0.1:6379> sadd set_test 1 2 3
(integer) 3
# 2. srem key element [element ...]
127.0.0.1:6379> srem set_test 2
(integer) 1
# 3. smembers key
127.0.0.1:6379> smembers set_test
1) "1"
2) "3"
127.0.0.1:6379> sscan set_test 0
1) "0"
2) 1) "1"
   2) "3"
  • 计算元素个数
# scard key
127.0.0.1:6379> scard set_test
(integer) 2
  • 判断元素是否存在
# sismember key element
127.0.0.1:6379> scard set_test
(integer) 2
127.0.0.1:6379> sismember set_test 1
(integer) 1
127.0.0.1:6379> sismember set_test 2
(integer) 0
  • 随机从集合返回指定个数元素
127.0.0.1:6379> sscan set_test 0
1) "0"
2) 1) "1"
   2) "3"
   3) "4"
   4) "5"
   5) "6"
   6) "7"
   7) "8"
# srandmember key [count]
127.0.0.1:6379> srandmember set_test 3
1) "8"
2) "3"
3) "6"
127.0.0.1:6379> sscan set_test 0
1) "0"
2) 1) "1"
   2) "3"
   3) "4"
   4) "5"
   5) "6"
   6) "7"
   7) "8"

注意喔,srandmember不会删除弹出的元素。

  • 从集合随机弹出元素
127.0.0.1:6379> sscan set_test 0
1) "0"
2) 1) "1"
   2) "3"
   3) "4"
   4) "6"
   5) "7"
   6) "8"
# spop key
127.0.0.1:6379> spop set_test
"6"
127.0.0.1:6379> sscan set_test 0
1) "0"
2) 1) "1"
   2) "3"
   3) "4"
   4) "7"
   5) "8"

注意喔,spop会删除弹出的元素。

集合间

127.0.0.1:6379> sadd s1 1 5 8
(integer) 3
127.0.0.1:6379> sadd s2 5 6 7 9
(integer) 4
127.0.0.1:6379> sadd s3 1 3 5 7 9
(integer) 5
127.0.0.1:6379> sinter s1 s2
1) "5"
127.0.0.1:6379> sunion s2 s3
1) "1"
2) "3"
3) "5"
4) "6"
5) "7"
6) "9"
127.0.0.1:6379> sdiff s1 s3
1) "8"

如何保存交、并、差集的结果?

# 1. sinterstore destination key [key ...]
127.0.0.1:6379> sinterstore set_inter s1 s2
(integer) 1
127.0.0.1:6379> sscan set_inter 0
1) "0"
2) 1) "5"

# 2. suionstore destination key [key ...]
127.0.0.1:6379> sunionstore set_union s2 s3
(integer) 6
127.0.0.1:6379> sscan set_union 0
1) "0"
2) 1) "1"
   2) "3"
   3) "5"
   4) "6"
   5) "7"
   6) "9"

# 3. sdiffstore destination key [key ...]
127.0.0.1:6379> sdiffstore set_diff s1 s3
(integer) 1
127.0.0.1:6379> sscan set_diff 0
1) "0"
2) 1) "8"

内部编码

集合类型也有两种内部编码:

  • intset
  • hashtable

证明:

127.0.0.1:6379> sadd set_test1 1
(integer) 1
127.0.0.1:6379> object encoding set_test1
"intset"
127.0.0.1:6379> sadd set_test1 yyc
(integer) 1
127.0.0.1:6379> object encoding set_test1
"hashtable"
127.0.0.1:6379> scard set_test2
(integer) 512
127.0.0.1:6379> object encoding set_test2
"intset"
127.0.0.1:6379> sadd set_test2 513
(integer) 1
127.0.0.1:6379> object encoding set_test2
"hashtable"

使用场景

  • 标签tag

Reference

  • 《Redis开发与运维》 - 2.5 集合


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory