Redis之set型別及操作

stonebox1122發表於2017-08-11
set是string型別的無序集合。透過hash table實現。

sadd:向名稱為key的set中新增元素,不能新增重複的元素。

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 world
(integer) 0
127.0.0.1:6379> smembers myset
1) "hello"
2) "world"

srem:刪除名稱為key的set中的元素。
127.0.0.1:6379> sadd myset2 one
(integer) 1
127.0.0.1:6379> sadd myset2 two
(integer) 1
127.0.0.1:6379> srem myset2 one
(integer) 1
127.0.0.1:6379> smembers myset2
1) "two"

spop:隨機返回並刪除名稱為key的set中一個元素。
127.0.0.1:6379> sadd myset3 one
(integer) 1
127.0.0.1:6379> sadd myset3 two
(integer) 1
127.0.0.1:6379> spop myset3
"two"
127.0.0.1:6379> smembers myset3
1) "one"

sdiff:返回所有給定key與第一個key的差集
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sdiff myset2 myset3
1) "three"

sdiffstore:返回所有給定key與第一個key的差集,並將結果存為另一個key。
127.0.0.1:6379> sdiffstore myset4 myset2 myset3
(integer) 1
127.0.0.1:6379> smembers myset4
1) "three"

sinter:返回所有給定key的交集。
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sinter myset2 myset3
1) "two"

sinterstore:返回所有給定key的交集,並將結果存為另一個key。
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sinterstore myset6 myset2 myset3
(integer) 1
127.0.0.1:6379> smembers myset6
1) "two"

sunion:返回所有給定key的並集。
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sunion myset2 myset3
1) "two"
2) "three"
3) "one"

sunionstore:返回所有給定key的並集,並將結果存為另一個key。
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sunionstore myset6 myset2 myset3
(integer) 3
127.0.0.1:6379> smembers myset6
1) "two"
2) "three"
3) "one"

smove:從第一個key對應的set中移除member並新增到第二個對應的set中。
127.0.0.1:6379> smembers myset2
1) "three"
2) "two"
127.0.0.1:6379> smove myset2 myset7 three
(integer) 1
127.0.0.1:6379> smembers myset2
1) "two"
127.0.0.1:6379> smembers myset7
1) "three"

scard:返回名稱為key的set的元素個數。
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> scard myset3
(integer) 2

sismember:測試member是否是名稱為key的set的元素
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> sismember myset3 two
(integer) 1
127.0.0.1:6379> sismember myset3 three
(integer) 0

srandmember:隨機返回名稱為key的set的一個元素,但不刪除元素。
127.0.0.1:6379> smembers myset3
1) "two"
2) "one"
127.0.0.1:6379> srandmember myset3
"one"
127.0.0.1:6379> srandmember myset3
"two"

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28536251/viewspace-2143378/,如需轉載,請註明出處,否則將追究法律責任。

相關文章