How to Return Field Values when using HRANDFIELD in Redis

In Redis, we can use the HRANDFIELD command to return random fields from a given hash. By default, only the field names are returned.

But what if we want to include the field values?

In this case, we can use the WITHVALUES option when calling the command.

Example

Here’s an example to demonstrate:

HRANDFIELD pet 1 WITHVALUES

Result:

1) "age"
2) "37"

Here, I returned one field and its respective value from a hash stored in a key called pets. In this case the field is called age, and its value is 37.

This option works for as many fields as we’re returning:

HRANDFIELD pet 3 WITHVALUES

Result:

1) "age"
2) "37"
3) "name"
4) "Wag"
5) "weight"
6) "10"

Error?

When we use the WITHVALUES argument, we need to also include the count argument, even if we’re only getting one field. Here’s what happens if I remove the count argument:

HRANDFIELD pet WITHVALUES

Result:

(error) ERR value is not an integer or out of range