In Redis, the SUNIONSTORE command does the same thing that SUNION does, except that it stores the result in a key. More specifically, it takes the members of the set resulting from the union of all of the given sets, and stores them in the specified key.
Syntax
The syntax goes like this:
SUNIONSTORE destination key [key ...]
Where destination is the key to store the result. We can pass one or more keys to the command.
Example
Suppose we create the following sets:
SADD cats Fluffy Scratch Meow
SADD dogs Wag Bark Fluffy
We can use SUNION to return the union of those two sets:
SUNIONSTORE animals cats dogs
Result:
(integer) 5
The command returns an integer reply with the number of members that were added to the set.
Our result indicates that five members were added to a set called animals.
We can verify the result by checking the contents of the newly created animals set:
SMEMBERS animals
Result:
1) "Bark" 2) "Scratch" 3) "Fluffy" 4) "Meow" 5) "Wag"
As expected, the set consists of five members.
Note that duplicate values are only included once. This makes sense, because sets can only contain unique values, and the result of SUNIONSTORE is a set. In our example, Fluffy appears in both the cats and dogs sets, but it only appears once in the animals set.
When the Destination Key Already Exists
If the destination key already exists, it’s overwritten:
SUNIONSTORE animals cats
Result:
(integer) 3
In this example, I specified the same destination key (animals) that we created in the previous example. That key was overwritten when I ran the code.
Here’s what the animals set contains now:
SMEMBERS animals
Result:
1) "Meow" 2) "Scratch" 3) "Fluffy"
Now the values from the dogs set are no longer in the animals set. That is because we only passed the cats set for the SUNIONSTORE operation, and the animals set was overwritten with the new result.
Wrong Argument Type
Passing a key that doesn’t contain a set results in an error:
SUNIONSTORE animals cats fruit
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Wrong Argument Count
Calling SUNIONSTORE with the wrong number of arguments results in an error:
SUNIONSTORE cats
Result:
(error) ERR wrong number of arguments for 'sunionstore' command