If you’re getting an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the Redis HSTRLEN
command, it’s probably because you’re running the command against a key that doesn’t contain a hash.
The HSTRLEN
command is a hash command, and is only intended to be used against hashes.
To fix this issue, be sure to run the command against a key that stores a hash. Alternatively, if you intend to run it against a different key type, then use a command designed for that key type.
Example of Error
Here’s an example of code that causes the error:
HSTRLEN color rgb
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the key holds a string (not a hash) and so we get the error.
We can verify this with the TYPE
command:
TYPE color
Result:
string
Yes it’s a string. The HSTRLEN
command doesn’t work on strings, which explains why we got the error.
To solve this issue, be sure to run the command against the correct key type.
Solution 1
If your intention is to run this against a hash, then make sure the key contains a hash:
HSTRLEN customer lastname
Result:
(integer) 7
In this case, I ran the command against a hash, and got the result I was looking for.
Solution 2
If your intention is to get the string length of a different data type, you’ll need to change to a more suitable command. The reason our color
key caused the error above is because it contains a string instead of a hash. In this case, if we really wanted to return the length of the string in that key, then we should use the STRLEN
command instead:
STRLEN color
Result:
(integer) 6
This time it worked for that key.
We can check the key’s value to verify this result:
GET color
Result:
"Yellow"
As expected, it has a string length of six.