redis 交集、並集、差集


sinter 、sunion 、sdiff

redis 支持 Set集合的數據存儲,其中有三個比較特殊的方法:

sinter key [key …] 返回一個集合的全部成員,該集合是所有給定集合的交集。
sunion key [key …] 返回一個集合的全部成員,該集合是所有給定集合的並集。
sdiff key [key …] 返回所有給定 key 與第一個 key 的差集

 

sinter 代碼示例

redis> SMEMBERS group_1
1) "LI LEI"
2) "TOM"
3) "JACK"

redis> SMEMBERS group_2
1) "HAN MEIMEI"
2) "JACK"

redis> SINTER group_1 group_2      # 取的是交集的數據 
1) "JACK"

 

sunion 代碼示例

redis> SMEMBERS songs
1) "Billie Jean"

redis> SMEMBERS my_songs
1) "Believe Me"

redis> SUNION songs my_songs       # 取的是集合的並集數據據
1) "Billie Jean"
2) "Believe Me"

 

sdiff 代碼示例

redis> SMEMBERS peter's_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SMEMBERS joe's_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SDIFF peter's_movies joe's_movies     # 取的是兩個集合的差集的數據
1) "bet man"

 

sinterstore、sunionstore、sdiffstore

sinterstore destination key [key …] 將 交集 數據存儲到某個對象中
sunionstore destination key [key …] 將 並集 數據存儲到某個對象中
sdiffstore destination key [key …] 將 差集 數據存儲到某個對象中

sinterstore 代碼示例

1) "good bye joe"
2) "hello,peter"

redis> SMEMBERS my_songs
1) "good bye joe"
2) "falling"

redis> SINTERSTORE song_interset songs my_songs           # 將交集的數據存儲到 song_interset 對象中
(integer) 1

redis> SMEMBERS song_interset                 # 返回 song_interset 對象中的 所有數據
1) "good bye joe"

 

sunionstore 代碼示例

redis> SMEMBERS NoSQL
1) "MongoDB"
2) "Redis"

redis> SMEMBERS SQL
1) "sqlite"
2) "MySQL"

redis> SUNIONSTORE db NoSQL SQL      # 將並集的數據存儲到 db 對象中
(integer) 4

redis> SMEMBERS db            # 返回 db 對象中的 所有數據
1) "MySQL"
2) "sqlite"
3) "MongoDB"
4) "Redis"

 

sdiffstore 代碼示例

redis> SMEMBERS joe's_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SMEMBERS peter's_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SDIFFSTORE joe_diff_peter joe's_movies peter's_movies          # 將差集的數據存儲到 joe_diff_peter 對象中
(integer) 2

redis> SMEMBERS joe_diff_peter              # 返回 joe_diff_peter 對象中的 所有數據
1) "hi, lady"
2) "Fast Five"

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM