Skip to content

Ask the HotKV docs

Answers come only from these docs and can be wrong; check the linked pages before you rely on them.

HRANDFIELD

Last updated
HRANDFIELD key [count [WITHVALUES]]
Group
Hash
Complexity
O(N) where N is the number of fields returned
Arity
-2 (at least 2 words, counting the command name)
Flags
read-only
Keys
first 1, last 1, step 1
HotKV Cloud
All plans
On-Premise
no license needed

HRANDFIELD picks random fields from the hash at key without changing it.

  • Without count, it returns one random field name.
  • With a positive count, it returns up to count distinct fields. If the hash has count fields or fewer, you get all of them.
  • With a negative count, it returns exactly |count| fields, and the same field can appear more than once.
  • A count of 0 returns an empty array.
Option Effect
count How many fields to return, as described above.
WITHVALUES Return each field together with its value. Only valid after count.

count and WITHVALUES are checked before the key is looked up, so a bad argument is an error even for a missing key.

Case RESP2 RESP3
No count Bulk string: a field name, or nil bulk string if the key does not exist Bulk string, or null
With count Array of field names (empty if the key does not exist) Same
With count and WITHVALUES Flat array: field, value, field, value, … Array of two-element arrays: [field, value]

Errors:

  • ERR value is not an integer or out of range if count is not an integer.
  • ERR value is out of range, value must between -9223372036854775807 and 9223372036854775807 for a count of -9223372036854775808.
  • ERR syntax error if the third argument is not WITHVALUES or there are extra arguments.
  • ERR count is too large, the reply would exceed 512 MB if a negative count would build a reply larger than 512 MB.
  • WRONGTYPE if key holds a value that is not a hash.
127.0.0.1:6379> HSET color r 255 g 128 b 0
(integer) 3
127.0.0.1:6379> HRANDFIELD color
"g"
127.0.0.1:6379> HRANDFIELD color 2 WITHVALUES
1) "b"
2) "0"
3) "r"
4) "255"
127.0.0.1:6379> HRANDFIELD color -4
1) "r"
2) "r"
3) "b"
4) "g"

The fields you get back are random, so your output will differ.

Same as Redis 7.4 and Valkey 8.

HGETALL, HSCAN, SRANDMEMBER, ZRANDMEMBER