If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the ZUNION or ZUNIONSTORE commands in Redis, it’s because you’re passing a key with the wrong data type.
To fix this issue, make sure the keys you pass to these commands contain either sets or sorted sets. Although these commands are for sorted sets, they also work with non-sorted sets.
Example of Error
Here’s an example of code that causes the error:
ZUNION 2 cats users
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In my case the users key holds a list, which is why I got the error. The cats key (correctly) contains a sorted set, but the users key containing the wrong data type was enough to cause the error.
We can use the TYPE command to check a key’s type:
TYPE users
Result:
list
As suspected, the key holds a list, which is the wrong data type for ZUNION (and for ZUNIONSTORE).
Solution
The solution is to make sure that each key we pass to the ZUNION and ZUNIONSTORE commands holds either a set or a sorted set.
Here’s an example that uses a set and a sorted set:
ZUNION 2 cats birds
Result:
1) "Fluffy" 2) "Flutter" 3) "Tweet" 4) "meow" 5) "fluffy" 6) "scratch"
This time it worked without error.
Let’s check both keys’ data types:
TYPE cats
Result:
zset
So, cats is a sorted set.
TYPE birds
Result:
set
And birds is actually a set (but not a sorted set), but it didn’t cause any errors.