If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the SMEMBERS
command in Redis, it’s probably because you’re passing a key with the wrong data type to the command.
The SMEMBERS
command is a “set” command, and so it is intended to be used on keys that contain a set. If the key holds a different data type, you’ll likely get the above error.
Example of Error
Here’s an example of code that causes the error:
SMEMBERS animals_desc
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the above error is returned. This tells us that the key holds the wrong kind of value.
Let’s use the TYPE
command to check the key’s type:
TYPE animals_desc
Result:
list
OK, so the animals_desc
key holds a list instead of a set. That’s why I get the error.
Solution 1
The solution to the issue will depend on what we’re trying to do. It could be that we’re passing the wrong key, in which case the solution is to pass the correct key. Or, it could be that we’re already passing the correct key, but we’re using the wrong command.
In my case, I’m trying to return the contents of a list, and so I’m using the wrong command. I should be using the LRANGE
command instead of the SMEMBERS
command:
LRANGE animals_desc 0 -1
Result:
1) "Zebra" 2) "Horse" 3) "Dog" 4) "Cow" 5) "Cat" 6) "Bird"
This time we got the list’s contents as expected.
Solution 2
Another possibility is that we’re using the correct command, but we’re passing the wrong key. In this case, all we need to do is make sure we pass the correct key.
Let’s try it with a different key:
SMEMBERS animals
Result:
1) "Horse" 2) "Dog" 3) "Cat" 4) "Cow" 5) "Bird" 6) "Zebra"
This time we used the SMEMBERS
command without error.
What happened in my case is that the animals
key contains a set, but the animals_desc
command contains a list.
This issue could arise after you use the SORT
command with the STORE
option to sort a key’s contents and store the results. This command returns the result as a list. Therefore, if you use SORT
on a set or sorted set, it will sort the contents and store the result as a list. After that, you may inadvertently use SMEMBERS
to get the results of the new key. But because the new key is not a list, you’ll get the above error.