If you’re getting an error that reads “ERR wrong number of arguments for ‘srandmember’ command” in Redis, it’s probably because you’re calling the SRANDMEMBER
command without any arguments.
To fix this issue, make sure you pass the correct number of arguments. At the time of writing, the SRANDMEMBER
command requires at least one argument, and accepts an optional second argument.
Example of Error
Here’s an example of code that produces the above error:
SRANDMEMBER
Result:
(error) ERR wrong number of arguments for 'srandmember' command
In this case, I called SRANDMEMBER
without any arguments, and so I got the error. This is because the command doesn’t know which key we want to get the random member from.
Solution
To fix the issue, simply pass at least one argument to specify which key to get the random member from.
The syntax for SRANDMEMBER
goes like this:
SRANDMEMBER key [count]
So, we must pass at least one argument.
Example:
SRANDMEMBER dogs
Result:
"Wag"
Here, I provided one argument, which is the name of the key that I want the random member returned from. That key is called dogs
.
We can alternatively provide a second argument to specify the number of random members we want returned:
SRANDMEMBER dogs 2
Result:
1) "Bark" 2) "Wag"
This time the results are returned in an array.
The above information is true at the time of writing. See the Redis documentation to check the latest specification for this command.