HRANDFIELD

HRANDFIELD key [count [WITHVALUES]]
Available since:
Redis Open Source 6.2.0
Time complexity:
O(N) where N is the number of fields returned
ACL categories:
@read, @hash, @slow,
Compatibility:
Redis Software and Redis Cloud compatibility

When called with just the key argument, return a random field from the hash value stored at key.

If the provided count argument is positive, return an array of distinct fields. The array's length is either count or the hash's number of fields (HLEN), whichever is lower.

If called with a negative count, the behavior changes and the command is allowed to return the same field multiple times. In this case, the number of returned fields is the absolute value of the specified count.

The optional WITHVALUES modifier changes the reply so it includes the respective values of the randomly selected hash fields.

Required arguments

key

The name of the key that holds the hash.

Optional arguments

count

The number of fields to return. A positive count returns up to that many distinct fields; a negative count returns exactly |count| fields and may repeat fields. When omitted, a single random field is returned.

WITHVALUES

Also return the value of each selected field. Can only be used together with count.

Examples

HSET coin heads obverse tails reverse edge null HRANDFIELD coin HRANDFIELD coin HRANDFIELD coin -5 WITHVALUES

Specification of the behavior when count is passed

When the count argument is a positive value this command behaves as follows:

  • No repeated fields are returned.
  • If count is bigger than the number of fields in the hash, the command will only return the whole hash without additional fields.
  • The order of fields in the reply is not truly random, so it is up to the client to shuffle them if needed.

When the count is a negative value, the behavior changes as follows:

  • Repeating fields are possible.
  • Exactly count fields, or an empty array if the hash is empty (non-existing key), are always returned.
  • The order of fields in the reply is truly random.

Redis Software and Redis Cloud compatibility

Redis
Software
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

Any of the following:

  • Nil reply: if the key doesn't exist
  • Bulk string reply: a single, randomly selected field when the count option is not used
  • Array reply: a list containing count fields when the count option is used, or an empty array if the key does not exists.
  • Array reply: a list of fields and their values when count and WITHVALUES were both used.
RATE THIS PAGE
Back to top ↑