If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the ZADD
command in Redis, it’s probably because you’re trying to update a key that contains the wrong data type.
To fix this issue, be sure to only use the ZADD
command against sorted sets if the key already exists. If the key doesn’t already exist, then you shouldn’t get this error.
Example of Error
Here’s an example of code that causes the error:
ZADD animals 10 Ruff
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
Here the animals
key contains a list instead of a sorted set and so we get an error.
We can use the TYPE
command to check the key’s data type:
TYPE animals
Result:
list
As suspected, the key contains a list instead of a sorted set.
Solution 1
If we’re trying to update an existing key, then we need to make sure that key contains the correct data type. The ZADD
command is designed to be used with sorted sets, so we should make sure the key contains a sorted set.
Here’s an example of running the command against a key that holds a sorted set:
ZADD dogs 10 Ruff
Result:
(integer) 1
This time we didn’t get the error because the dogs
key holds a sorted set.
Let’s verify the data type with the TYPE
command:
TYPE dogs
Result:
zset
As expected, it’s a sorted set (zset
means sorted set).
Solution 2
Another way to deal with the issue is to create a whole new sorted set. If the key doesn’t already exist, the ZADD
command creates it and adds the specified member to it.
Example:
ZADD my_animals 10 Ruff
Result:
(integer) 1
We didn’t get the error because the my_animals
key didn’t exist. Therefore it was created as a sorted set, and the specified value was added to it with the corresponding score.
Let’s take a look at it:
ZRANGE my_animals 0 -1 WITHSCORES
Result:
1) "Ruff" 2) "10"
All good.