Set Operations
Server-side set algebra
Section titled “Server-side set algebra”Redis can compute intersection, union, and difference between two or more Sets entirely on the server. You never need to pull all members to the client and compute locally.
SINTER — intersection
Section titled “SINTER — intersection”SINTER key [key ...] returns only the members that appear in every listed Set. Classic use case: mutual friends.
127.0.0.1:6379> SADD user:1:follows "alice" "bob" "carol" "dave"(integer) 4127.0.0.1:6379> SADD user:2:follows "bob" "carol" "eve" "frank"(integer) 4127.0.0.1:6379> SINTER user:1:follows user:2:follows1) "bob"2) "carol"SADD user:1:follows "alice" "bob" "carol" "dave"
SADD user:2:follows "bob" "carol" "eve" "frank"
SINTER user:1:follows user:2:followsSUNION — union
Section titled “SUNION — union”SUNION key [key ...] returns all members from any of the listed Sets, deduplicated. Use case: combined audience across campaigns.
127.0.0.1:6379> SADD campaign:A "user:1" "user:2" "user:3"(integer) 3127.0.0.1:6379> SADD campaign:B "user:2" "user:4" "user:5"(integer) 3127.0.0.1:6379> SUNION campaign:A campaign:B1) "user:1"2) "user:2"3) "user:3"4) "user:4"5) "user:5"SADD campaign:A "user:1" "user:2" "user:3"
SADD campaign:B "user:2" "user:4" "user:5"
SUNION campaign:A campaign:BSDIFF — difference
Section titled “SDIFF — difference”SDIFF key [key ...] returns members in the first Set that do not appear in any subsequent Set. Use case: find users in one group but not another.
127.0.0.1:6379> SADD plan:premium "user:1" "user:2" "user:3"(integer) 3127.0.0.1:6379> SADD notified:promo "user:2" "user:3"(integer) 2127.0.0.1:6379> SDIFF plan:premium notified:promo1) "user:1"SADD plan:premium "user:1" "user:2" "user:3"
SADD notified:promo "user:2" "user:3"
SDIFF plan:premium notified:promoSINTERSTORE, SUNIONSTORE, SDIFFSTORE
Section titled “SINTERSTORE, SUNIONSTORE, SDIFFSTORE”The *STORE variants write the result to a destination key instead of returning it. The destination is a regular Set you can inspect later.
127.0.0.1:6379> SADD group:eng "alice" "bob" "carol"(integer) 3127.0.0.1:6379> SADD group:ops "carol" "dave"(integer) 2127.0.0.1:6379> SINTERSTORE overlap:eng-ops group:eng group:ops(integer) 1127.0.0.1:6379> SMEMBERS overlap:eng-ops1) "carol"127.0.0.1:6379> SUNIONSTORE all:staff group:eng group:ops(integer) 4127.0.0.1:6379> SMEMBERS all:staff1) "alice"2) "bob"3) "carol"4) "dave"SADD group:eng "alice" "bob" "carol"
SADD group:ops "carol" "dave"
SINTERSTORE overlap:eng-ops group:eng group:ops
SMEMBERS overlap:eng-ops
SUNIONSTORE all:staff group:eng group:ops
SMEMBERS all:staff