Redis集合是未排序的集合,其元素是二进制安全的字符串。
和List不同的是,Set集合中不允许出现重复的元素。另外set可以进行集合操作,比如合并,交集,差集。
添加元素
127.0.0.1:6442> sadd set1 a1 a2 a3
(integer) 3
127.0.0.1:6442> smembers set1
1) "a1"
2) "a2"
3) "a3"
127.0.0.1:6442> sadd set1 a1 a4 a5
(integer) 2
127.0.0.1:6442> smembers set1
1) "a1"
2) "a2"
3) "a4"
4) "a3"
5) "a5"
判断元素是否存在
127.0.0.1:6442> sismember set1 a1
(integer) 1
127.0.0.1:6442> sismember set1 a6
(integer) 0
列出某个key键中所有的元素
127.0.0.1:6442> smembers set1
1) "a4"
2) "a3"
3) "a1"
4) "a2"
5) "a5"
列出某个key键中元素个数
127.0.0.1:6442> scard set1
(integer) 5
随机取出一个元素
127.0.0.1:6442> srandmember set1
"a3"
127.0.0.1:6442> srandmember set1
"a1"
127.0.0.1:6442> srandmember set1
"a4"
删除指定的元素
127.0.0.1:6442> srem set1 a1
(integer) 1
127.0.0.1:6442> smembers set1
1) "a2"
2) "a5"
3) "a4"
4) "a3"
移除集合中的一个元素并返回该元素
127.0.0.1:6442> spop set1
"a2"
127.0.0.1:6442> smembers set1
1) "a5"
2) "a4"
3) "a3"
将集合中的一个元素移到另外一个集合中
127.0.0.1:6442> sadd set2 b1 b2 b3
(integer) 3
127.0.0.1:6442> smembers set2
1) "b3"
2) "b2"
3) "b1"
127.0.0.1:6442> smembers set1
1) "a5"
2) "a4"
3) "a3"
127.0.0.1:6442> smembers set2
1) "b3"
2) "b2"
3) "b1"
127.0.0.1:6442> smove set1 set2 a1
(integer) 0
127.0.0.1:6442> smove set1 set2 a5
(integer) 1
127.0.0.1:6442> smembers set1
1) "a4"
2) "a3"
127.0.0.1:6442> smembers set2
1) "a5"
2) "b3"
3) "b2"
4) "b1"
返回集合差集
127.0.0.1:6442> smembers set1
1) "c1"
2) "c2"
3) "a5"
4) "a4"
5) "a3"
127.0.0.1:6442> smembers set2
1) "c1"
2) "b3"
3) "b2"
4) "b1"
5) "c2"
127.0.0.1:6442> sdiff set1 set2
1) "a5"
2) "a4"
3) "a3"
将集合差集保存到一个集合中
127.0.0.1:6442> sadd set1 a1 a2 a3
(integer) 3
127.0.0.1:6442> sadd set2 b1 b2 b3
(integer) 3
127.0.0.1:6442> sadd set3 c1 c2 c3
(integer) 3
127.0.0.1:6442> sdiffstore set4 set1 set2 set3
(integer) 3
127.0.0.1:6442> smembers set1
1) "a1"
2) "a2"
3) "a3"
127.0.0.1:6442> smembers set2
1) "b3"
2) "b2"
3) "b1"
127.0.0.1:6442> smembers set3
1) "c1"
2) "c3"
3) "c2"
127.0.0.1:6442> smembers set4
1) "a1"
2) "a2"
3) "a3"
返回集合交集
127.0.0.1:6442> smembers set1
1) "a1"
2) "a2"
3) "d1"
4) "a3"
5) "d2"
127.0.0.1:6442> smembers set2
1) "b3"
2) "d1"
3) "b2"
4) "b1"
5) "d2"
127.0.0.1:6442> smembers set3
1) "c1"
2) "c3"
3) "d1"
4) "c2"
5) "d2"
127.0.0.1:6442> smembers set4
1) "a1"
2) "a2"
3) "a3"
127.0.0.1:6442> sinter set1 set2
1) "d1"
2) "d2"
127.0.0.1:6442> sinter set1 set2 set3
1) "d1"
2) "d2"
将集合交集保存到一个集合中
127.0.0.1:6442> sinterstore set5 set1 set2 set3
(integer) 2
127.0.0.1:6442> smembers set5
1) "d2"
2) "d1"
返回集合并
127.0.0.1:6442> sunion set1 set2
1) "d1"
2) "b2"
3) "b1"
4) "a1"
5) "d2"
6) "a2"
7) "b3"
8) "a3"
将集合并集保存到一个集合中
127.0.0.1:6442> sunionstore set6 set1 set2
(integer) 8
127.0.0.1:6442> smembers set6
1) "d1"
2) "b2"
3) "b1"
4) "a1"
5) "d2"
6) "a2"
7) "b3"
8) "a3"
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25105315/viewspace-2122042/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/25105315/viewspace-2122042/