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 the key you pass to the ZINTER
command holds a sorted set.
Example of Error
Here’s an example of code that causes the error:
ZINCRBY country 3 Australia
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Here the country
key contains a string and so we get an error.
I get the same error when I run the code against a (non-sorted) set:
ZINCRBY countries 3 Australia
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case the countries
key holds a (non-sorted) set, and so we get the same error.
Solution
The solution is to make sure the key we pass contains the correct data type. The ZINCRBY
command is designed to be used on sorted sets, so we should make sure the specified key contains a sorted set.
Here’s an example of running the command against a key that holds a sorted set:
ZINCRBY cats 3 meow
Result:
"4"
This time we didn’t get the error because the key holds a sorted set.
In this case, the member was incremented by 3, which resulted in it having a score of 4 (its original score was 1).
Check a Key’s Data Type
If you’re not sure whether or not a key contains a sorted set, you can use the TYPE
command to check its data type:
TYPE country
Result:
string
This example confirms why we got the error earlier on. The country
key contains a string instead of a sorted set.
Let’s check the countries
key:
TYPE countries
Result:
set
The countries
key contains a set, but it’s not a sorted set. That’s why we got the error when we passed it to the ZINCRBY
command in the earlier example.