Redis五大数据类型之Set
Posted 王六六的IT日常
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis五大数据类型之Set相关的知识,希望对你有一定的参考价值。
Redis 概述
五大数据类型
1.String(字符串)
2.List(列表)
3.Set(集合)
set中的值是不能重复的!命令是s
开头。
添加(sadd
)、查看元素(smembers
)、查看指定元素(sismember
)
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> sadd myset "hello" # set集合中添加元素
(integer) 1
127.0.0.1:6379> sadd myset "wangliuliu"
(integer) 1
127.0.0.1:6379> sadd myset "lovewangliuliu"
(integer) 1
127.0.0.1:6379> smembers myset # 查看指定set的所有值
1) "hello"
2) "lovewangliuliu"
3) "wangliuliu"
127.0.0.1:6379> sismember myset hello # 判断某一个值是不是在set集合中!
(integer) 1
127.0.0.1:6379> sismember myset world
(integer) 0
获取个数 scard
127.0.0.1:6379> smembers myset
1) "hello"
2) "lovewangliuliu"
3) "wangliuliu"
127.0.0.1:6379> scard myset # 获取set集合中的内容元素个数
(integer) 3
移除集合元素(srem
)
127.0.0.1:6379> smembers myset
1) "hello"
2) "lovewangliuliu"
3) "wangliuliu"
127.0.0.1:6379> srem myset hello # 移除set集合中的指定元素
(integer) 1
127.0.0.1:6379> scard myset
(integer) 2
127.0.0.1:6379> smembers myset
1) "lovewangliuliu"
2) "wangliuliu"
set 无序不重复集合,抽随机(srandmember
)
127.0.0.1:6379> smembers myset
1) "lovewangliuliu"
2) "wangliuliu"
3) "lovewanzi"
127.0.0.1:6379> srandmember myset # 随机抽选出一个元素
"lovewanzi"
127.0.0.1:6379> srandmember myset # 随机抽选出一个元素
"lovewangliuliu"
127.0.0.1:6379> srandmember myset 2 # 随机抽选出指定个数的元素
1) "wangliuliu"
2) "lovewangliuliu"
随机删除(spop
)
127.0.0.1:6379> smembers myset
1) "lovewangliuliu"
2) "wangliuliu"
3) "lovewanzi"
127.0.0.1:6379> spop myset # 随机删除一些set集合中的元素
"lovewanzi"
127.0.0.1:6379> spop myset
"wangliuliu"
127.0.0.1:6379> smembers myset
1) "lovewangliuliu"
smove
将一个指定的值,移动到另外一个set集合
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> sadd myset "hello"
(integer) 1
127.0.0.1:6379> sadd myset "world"
(integer) 1
127.0.0.1:6379> sadd myset "wanzi"
(integer) 1
127.0.0.1:6379> sadd myset1 "set1"
(integer) 1
127.0.0.1:6379> smembers myset
1) "world"
2) "hello"
3) "wanzi"
127.0.0.1:6379> smembers myset1
1) "set1"
127.0.0.1:6379> smove myset myset1 "wanzi" # 将一个指定的值wanzi,移动到另外一个set集合
(integer) 1
127.0.0.1:6379> smembers myset
1) "world"
2) "hello"
127.0.0.1:6379> smembers myset1
1) "wanzi"
2) "set1"
数字集合类:
- 差集
sdiff
- 交集
sinter
- 并集
sunion
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> sadd key1 a
(integer) 1
127.0.0.1:6379> sadd key1 b
(integer) 1
127.0.0.1:6379> sadd key1 c
(integer) 1
127.0.0.1:6379> sadd key2 c
(integer) 1
127.0.0.1:6379> sadd key2 d
(integer) 1
127.0.0.1:6379> sadd key2 e
(integer) 1
127.0.0.1:6379> smembers key1
1) "c"
2) "b"
3) "a"
127.0.0.1:6379> smembers key2
1) "c"
2) "e"
3) "d"
127.0.0.1:6379> sdiff key1 key2 # 差集以key1为参照
1) "a"
2) "b"
127.0.0.1:6379> sinter key1 key2 #交集
1) "c"
127.0.0.1:6379> sunion key1 key2 #并集
1) "c"
2) "e"
3) "a"
4) "b"
5) "d"
微博,A用户将所有关注的人放在一个set集合中!
将它的粉丝也放在一个集合中!
共同关注,共同爱好,二度好友,推荐好友!(六度分割理论)
以上是关于Redis五大数据类型之Set的主要内容,如果未能解决你的问题,请参考以下文章