If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the ZINTERSTORE
command in Redis, it’s probably because you’re passing a key with the wrong data type.
To fix this issue, be sure that each key you pass to the ZINTERSTORE
command is either a set or a sorted set.
We can get the same error when using the ZINTER
command, and we can fix it in the same way.
Example of Error
Here’s an example of code that causes the error:
ZINTERSTORE animals 2 cats country
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In my case, the cats
key holds a sorted set but the country
key holds a string, which is why I got the error.
We can use the TYPE
command to check a key’s type:
TYPE country
Result:
string
As suspected, the key holds a string, which is the wrong data type for the ZINTERSTORE
command.
The cats
key is fine though:
TYPE cats
Result:
zset
This means that it’s a sorted set, which is the correct data type.
Solution
The solution is to make sure the keys we pass contain the correct data type. The ZINTERSTORE
command is designed to be used on sorted sets, but it can also work on (non-sorted) sets, so we should make sure the keys contain one of those data types. The same is true for the ZINTER
command.
In our above example, the cats
key is fine (because it holds a sorted set) but the country
key is what caused the error. This is because it doesn’t hold a sorted set (it holds a string).
Let’s replace the country
key with another key that holds a sorted set:
ZINTERSTORE animals 2 cats dogs
Result:
(integer) 2
This time we didn’t get the error. That’s because both keys hold a sorted set.
As mentioned non-sorted sets are also fine:
ZINTERSTORE animals 2 cats users
Result:
(integer) 2
Here, I replaced the dogs
key with one called users
. The users
key actually holds a (non-sorted) set. We can verify this with the TYPE
command:
TYPE users
Result:
set
As suspected, it’s a set, but it doesn’t cause any issues with the ZINTERSTORE
command.