redis中Set集合SortSet有序集合的復制
redis中Set集合SortSet有序集合的復制
redis集合類型中是沒有復制命令的,我所說的復制,是通過redis
的其他指令來實現
需求:將key1的內容全部拷貝到key2中
下面我們來看看在redis中怎么處理
Set集合的復制
首先,我們創建一個集合key1,這時key2還沒有創建
127.0.0.1:6380[1]> SADD key1 "a" (integer) 1 127.0.0.1:6380[1]> SADD key1 "b" (integer) 1 127.0.0.1:6380[1]> SADD key1 "c" (integer) 1 127.0.0.1:6380[1]> smembers key1 1) "b" 2) "a" 3) "c"
然后將key1拷貝到key2中
127.0.0.1:6380[1]> SUNIONSTORE key2 key1 temp (integer) 3 127.0.0.1:6380[1]> smembers key1 1) "b" 2) "a" 3) "c" 127.0.0.1:6380[1]> smembers key2 1) "a" 2) "b" 3) "c" 127.0.0.1:6380[1]> smembers temp (empty list or set)
上面例子中的temp是一個不存在的key
如果key2是已經存在的key,也可以進行復制,不過這個時候,就是將key1中所有內容都移動key2中。
127.0.0.1:6380[1]> SADD key1 "d" (integer) 1 127.0.0.1:6380[1]> SADD key1 "e" (integer) 1 127.0.0.1:6380[1]> smembers key1 1) "d" 2) "b" 3) "a" 4) "c" 5) "e" 127.0.0.1:6380[1]> SUNIONSTORE key2 key1 temp (integer) 5 127.0.0.1:6380[1]> smembers key2 1) "a" 2) "b" 3) "d" 4) "c" 5) "e" 127.0.0.1:6380[1]> smembers temp (empty list or set)
使用SUNIONSTORE命令可以很容易的實現Set的復制,下面我們看看SUNIONSTORE命令的使用方式:
語法:
SUNIONSTORE destination key [key ...]
- destination:存放合並結果集的key。
- key [key …]:一個或者多個集合
注意:
如果是已經存在的集合,會刪除原來的數據,只會保留合並結果。
下面創建了一個key3,在key3中有一個成員 “g” ,但是將key1和key2使用SUNIONSTORE命令合並后,結果中不會有 “g” 。
127.0.0.1:6380[1]> sunionstore key3 key1 key2 (integer) 5 127.0.0.1:6380[1]> sadd key1 f h i (integer) 3 127.0.0.1:6380[1]> sadd key3 g (integer) 1 127.0.0.1:6380[1]> smembers key3 1) "b" 2) "a" 3) "e" 4) "d" 5) "c" 6) "g" 127.0.0.1:6380[1]> smembers key1 1) "a" 2) "b" 3) "e" 4) "d" 5) "i" 6) "h" 7) "c" 8) "f" 127.0.0.1:6380[1]> sunionstore key3 key1 key2 (integer) 8 127.0.0.1:6380[1]> smembers key3 1) "b" 2) "a" 3) "i" 4) "h" 5) "e" 6) "d" 7) "c" 8) "f"
SortSet有序集合的復制
首先也來創建一個有序集合zset1, 這時候沒有zset2這個key
127.0.0.1:6380[1]> zadd zset1 1 a 2 b 3 c 4 d 5 e (integer) 5 127.0.0.1:6380[1]> zrange zset1 0 -1 1) "a" 2) "b" 3) "c" 4) "d" 5) "e"
然后將zset1拷貝到zset2中
127.0.0.1:6380[1]> ZUNIONSTORE zset2 1 zset1
(integer) 5
提示有5條內容被處理,然后我們來看看zset2現在的內容:
127.0.0.1:6380[1]> zrange zset2 0 -1 1) "a" 2) "b" 3) "c" 4) "d" 5) "e"
太帥了!跟zset1的內容一模一樣。
這一切都是ZUNIONSTORE這個命令的功勞,下面我們講講這個ZUNIONSTORE命令怎么用吧:
語法:
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight] [SUM|MIN|MAX]
ZUNIONSTORE命令其實就是求並集的命令,他的參數說明如下:
- destination: 存放合並結果集的key。如果是已經存在的集合,會刪除原來的數據,只會保留合並結果。
- numkeys:有幾個集合的內容需要合並
- key [key …]: 一個或者多個集合
- [WEIGHTS weight]:分數乘積因子,默認是1.如果設置以后,在合並時,會將待合並的集合中的分數乘以乘積因子,然后將結果保存到合並結果集中。
- [SUM|MIN|MAX]:結果集的聚合方式。默認是SUM,如果要合並的集合中都有同一個名稱的元素,它們的分數以何種方式存儲到新的結果集中。SUM:相加;MIN:取最小的值;MAX:取最大的值。