HRANDFIELD
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 tocountdistinct fields. If the hash hascountfields 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
countof0returns an empty array.
Options
Section titled “Options”| 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.
Return value
Section titled “Return value”| 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 rangeifcountis not an integer.ERR value is out of range, value must between -9223372036854775807 and 9223372036854775807for acountof -9223372036854775808.ERR syntax errorif the third argument is notWITHVALUESor there are extra arguments.ERR count is too large, the reply would exceed 512 MBif a negativecountwould build a reply larger than 512 MB.WRONGTYPEifkeyholds a value that is not a hash.
Examples
Section titled “Examples”127.0.0.1:6379> HSET color r 255 g 128 b 0(integer) 3127.0.0.1:6379> HRANDFIELD color"g"127.0.0.1:6379> HRANDFIELD color 2 WITHVALUES1) "b"2) "0"3) "r"4) "255"127.0.0.1:6379> HRANDFIELD color -41) "r"2) "r"3) "b"4) "g"The fields you get back are random, so your output will differ.
Compatibility
Section titled “Compatibility”Same as Redis 7.4 and Valkey 8.
See also
Section titled “See also”Was this page helpful?
Thanks for the feedback.