In Redis, the SINTERSTORE
command is the same as the SINTER
command, except that it stores the result in the specified key, instead of returning it.
It stores the members of the set resulting from the intersection of all the given sets.
If the destination key already exists, it’s overwritten. If it doesn’t exist, it’s created and the resulting members are added to it.
Syntax
The syntax goes like this:
SINTERSTORE destination key [key ...]
Example
Suppose we create the following sets:
SADD set1 0 1 2 3 4 5 6
SADD set2 5 6 7 8
We can use the SINTERSTORE
command to store the members of the set resulting from the intersection of both sets in a specified key:
SINTERSTORE results1 set1 set2
Result:
(integer) 2
The result is an integer reply of 2
, which means that two members were added to the destination key. In my case, the key didn’t already exist and so it was created and the resulting members were added to it.
Let’s check the resulting key:
SMEMBERS results1
Result:
1) "5" 2) "6"
We get 5
and 6
, because those two members are in both sets.
Now let’s create another set:
SADD set3 1 4 5
Now let’s include that as a set when calling the SINTERSTORE
command:
SINTERSTORE results2 set1 set2 set3
Result:
(integer) 1
An integer reply of 1
indicates that only one member was added to the resulting set.
Let’s take a look at the resulting set:
SMEMBERS results2
Result:
1) "5"
This time only 5
is returned. That’s because it’s the only member that’s common to all sets.
Let’s remove the second set when calling SINTERSTORE
:
SINTERSTORE result3 set1 set3
Result:
(integer) 3
Three members were added to the resulting set.
Check the resulting set:
SMEMBERS result3
Result:
1) "1" 2) "4" 3) "5"
More values are returned this time.
Non-Existent Keys
Keys that don’t exist are treated as empty sets. If we pass an empty set to the SINTERSTORE
command, the result will be zero, because any intersection with an empty set will always result in an empty set.
Example:
SINTERSTORE result4 set1 nonexistentkey
Result:
(integer) 0
When the Destination Key Already Exists
If the destination key already exists, it’s overwritten.
Let’s check the current value of the results1
key:
SMEMBERS results1
Result:
1) "5" 2) "6"
Now let’s run SINTERSTORE
and store the result in that key:
SINTERSTORE results1 set1 set3
Result:
(integer) 3
Three items were added. These are different to the original values, because we ran SINTERSTORE
against different sets.
Let’s check the key again:
SMEMBERS results1
Result:
1) "1" 2) "4" 3) "5"
It has been overwritten with the new values as expected.