If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the ZINTER
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 ZINTER
command is either a set or a sorted set.
Example of Error
Here’s an example of code that causes the error:
ZINTER 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 ZINTER
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 ZINTER
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.
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:
ZINTER 2 cats dogs
Result:
1) "fluffy" 2) "scratch"
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:
ZINTER 2 cats users
Result:
1) "fluffy" 2) "scratch"
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 ZINTER
command.