Set
-
Redis 的 Set 是 String 型別的無序集合。集合成員是唯一的,這就意味著集合中不能出現重複的資料。(無序不重複)
-
集合物件的編碼可以是 intset 或者 hashtable。
-
Redis 中集合是透過雜湊表實現的,所以新增,刪除,查詢的複雜度都是 O(1)。
案例
127.0.0.1:6379> SADD myset hello #set集合中新增元素
(integer) 1
127.0.0.1:6379> SADD myset lili
(integer) 1
127.0.0.1:6379> SADD myset love ll
(integer) 2
127.0.0.1:6379> SMEMBERS myset #檢視指定set的所有值
1) "love"
2) "lili"
3) "ll"
4) "hello"
127.0.0.1:6379> SISMEMBER myset hello #判斷某一個值是否存在set中
(integer) 1
127.0.0.1:6379> SISMEMBER myset lili
(integer) 1
- scard
127.0.0.1:6379> scard myset #獲取set集合中元素的個數
(integer) 4
- SREM
127.0.0.1:6379> SREM myset hello #移除set中的指定元素
(integer) 1
127.0.0.1:6379> SMEMBERS myset
1) "love"
2) "lili"
3) "ll"
- SMEMBERS
127.0.0.1:6379> SMEMBERS myset #隨機抽取set中的一個元素
1) "love"
2) "lili"
3) "ll"
127.0.0.1:6379> SRANDMEMBER myset
"love"
127.0.0.1:6379> SRANDMEMBER myset
"ll"
127.0.0.1:6379> SRANDMEMBER myset
"love"
127.0.0.1:6379> SRANDMEMBER myset
"ll"
127.0.0.1:6379> SRANDMEMBER myset 2 #隨機抽取指定個數的元素
1) "lili"
2) "ll"
127.0.0.1:6379> SRANDMEMBER myset 2
1) "love"
2) "ll"
- SPOP
127.0.0.1:6379> SMEMBERS myset
1) "love"
2) "lili"
3) "ll"
127.0.0.1:6379> SPOP myset #隨機刪除set集合中的一個元素
"ll"
127.0.0.1:6379> SPOP myset
"love"
127.0.0.1:6379> SMEMBERS myset
1) "lili"
- SMOVE
127.0.0.1:6379> SADD myset hello
(integer) 1
127.0.0.1:6379> SADD myset hello1
(integer) 1
127.0.0.1:6379> SADD myset hello2
(integer) 1
127.0.0.1:6379> SADD myset hello3
(integer) 1
127.0.0.1:6379> SADD myset2 set2
(integer) 1
127.0.0.1:6379>
127.0.0.1:6379> SMOVE myset myset2 hello #將一個指定的值移動到另外以一個set
(integer) 1
127.0.0.1:6379> smembers myset
1) "hello3"
2) "hello1"
3) "hello2"
127.0.0.1:6379> smembers myset2
1) "hello"
2) "set2"
- SDIFF&SINTER&sunion
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> SDIFF key1 key2 #差集,a和b做差集 = a有的b沒有,前邊集合和後邊集合作比較,找出前邊集合和後邊集合不同的
1) "a"
2) "b"
127.0.0.1:6379> SINTER key1 key2 #交集
1) "c"
127.0.0.1:6379> sunion key1 key2 #並集
1) "d"
2) "b"
3) "c"
4) "a"
5) "e"