Redis 交集、并集、差集

一、sinter 、sunion 、sdiff

redis 支持 Set集合的數(shù)據(jù)存儲(chǔ),其中有三個(gè)比較特殊的方法:

  • sinter key [key …] 查看一個(gè)集合的全部成員,該集合是所有給定集合的交集。
  • sunion key [key …] 查看一個(gè)集合的全部成員,該集合是所有給定集合的并集。
  • sdiff key [key …] 查看所有給定 key 與第一個(gè) key 的差集

1.1、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      # 取的是交集的數(shù)據(jù) 
1) "JACK"

1.2、sunion 并集的示例

redis> SMEMBERS songs
1) "Billie Jean"

redis> SMEMBERS my_songs
1) "Believe Me"

redis> SUNION songs my_songs       # 取的是集合的并集數(shù)據(jù)據(jù)
1) "Billie Jean"
2) "Believe Me"

1.3、sdiff 差集的示例

redis> SMEMBERS peter_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SMEMBERS joe_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SDIFF peter_movies joe_movies     # 取的是兩個(gè)集合的差集的數(shù)據(jù)
1) "bet man"
2) "start war"

二、sinterstore、sunionstore、sdiffstore

  • sinterstore destination key [key …] 將 交集 數(shù)據(jù)存儲(chǔ)到某個(gè)對(duì)象中
  • sunionstore destination key [key …] 將 并集 數(shù)據(jù)存儲(chǔ)到某個(gè)對(duì)象中
  • sdiffstore destination key [key …] 將 差集 數(shù)據(jù)存儲(chǔ)到某個(gè)對(duì)象中

2.1、sinterstore 交集的示例

redis> SMEMBERS songs
1) "good bye joe"
2) "hello,peter"

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

redis> SINTERSTORE song_interset songs my_songs           # 將交集的數(shù)據(jù)存儲(chǔ)到 song_interset 對(duì)象中
(integer) 1

redis> SMEMBERS song_interset                 # 查看 song_interset 對(duì)象中的 所有數(shù)據(jù)
1) "good bye joe"

2.2、sunionstore 并集的示例

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

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

redis> SUNIONSTORE db NoSQL SQL      # 將并集的數(shù)據(jù)存儲(chǔ)到 db 對(duì)象中
(integer) 4

redis> SMEMBERS db            # 查看 db 對(duì)象中的 所有數(shù)據(jù)
1) "MySQL"
2) "sqlite"
3) "MongoDB"
4) "Redis"

2.3、sdiffstore 差集的示例

redis> SMEMBERS joe_movies
1) "hi, lady"
2) "Fast Five"
3) "2012"

redis> SMEMBERS peter_movies
1) "bet man"
2) "start war"
3) "2012"

redis> SDIFFSTORE joe_diff_peter  joe_movies  peter_movies          # 將差集的數(shù)據(jù)存儲(chǔ)到 joe_diff_peter 對(duì)象中
(integer) 2

redis> SMEMBERS joe_diff_peter              # 查看 joe_diff_peter 對(duì)象中的 所有數(shù)據(jù)
1) "hi, lady"
2) "Fast Five"
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容