Fix “ERR wrong number of arguments for ‘hrandfield’ command” in Redis

If you’re getting an error that reads “ERR wrong number of arguments for ‘hrandfield’ command“, it’s probably because you’re not passing any arguments when using the HRANDFIELD command.

The HRANDFIELD command requires at least one argument, and accepts up to three arguments (at the time of writing).

I find that this error only occurs when I don’t pass any arguments. If I pass too many arguments, I get a different error.

If you’re getting this error, check the number of arguments that you’re passing and adjust if required.

Example of Error

Here’s an example of code that produces the error:

HRANDFIELD

Result:

(error) ERR wrong number of arguments for 'hrandfield' command

In this case I called HRANDFIELD without any arguments. It requires at least one argument – the key from which to return the random field/s.

Solution

To solve this issue, we need to pass the name of the key from which to return the random field/s:

HRANDFIELD pet

Result:

"height"

This time we get the result we’re looking for.

In this example I pass just one argument, but I could have passed some more optional arguments (depending on my requirements). Either way, the reason I got the above error was that I wasn’t passing any arguments.