If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when setting a hash with a command like HSET
or HSETNX
, it’s probably because you’re trying to set a non-hash key that already exists. In other words, the key already exists, but it doesn’t contain a hash.
To fix this issue, be sure to use these commands on keys that either don’t already exist, or contain a hash.
Example of Error
Here’s an example of code that causes the error:
HSET color rgb "0000FF" name "Blue"
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the color
key is actually a string. So Redis prevented it from being updated and returned this error message.
Solution
As mentioned, to fix this issue, be sure to use these commands on keys that either don’t already exist, or contain a hash.
Here’s an example of setting a key that doesn’t already exist:
HSET color_ref rgb "0000FF" name "Blue"
Result:
(integer) 2
Here, I changed the name of the key to one that doesn’t exist.
And here’s an example of setting a key that already exists and contains a hash:
HSET color_ref rgb "FF0000" name "Red"
Result:
(integer) 0
Here, 0
is returned because no fields were added. However, the key was still updated with the new values:
HGETALL color_ref
Result:
1) "rgb" 2) "FF0000" 3) "name" 4) "Red"