Sample one candidate setting
Feature flags or configuration hashes
Redis · Module
Returns one or more randomly selected fields from a hash. Positive counts select distinct fields up to the hash size; negative counts allow repeats, and WITHVALUES also returns the selected values.
HRANDFIELD samples fields from the hash at key. Without count it returns one field; a positive count requests distinct fields up to the hash size, while a negative count requests exactly the absolute count and permits repeats. WITHVALUES adds each selected field's value and requires count.
HRANDFIELD key [count [WITHVALUES]]| Name | Type | Description |
|---|---|---|
key | string | The name of the key that holds the hash. |
count | integer, optional | The number of fields to return. Positive values request up to that many distinct fields; negative values request exactly the absolute value and may repeat fields. If omitted, one field is returned. |
WITHVALUES | modifier, optional | Also return the value of each selected field; usable only with count. |
A single field when count is omitted; otherwise an array of fields, or fields and values when count and WITHVALUES are both used. A negative count returns an empty array for an empty or missing hash.
HSET coin heads 60 tails 40
HRANDFIELD coin
HRANDFIELD coin 2
HRANDFIELD coin -5 WITHVALUESCreates a hash, selects one random field, selects up to two distinct fields, then requests five selections with their values; the final command may repeat fields.
Feature flags or configuration hashes
Randomized menus and recommendations
Weighted or repeated trials represented by hash fields
Cache inspection or randomized diagnostics
Without count, HRANDFIELD returns one random field. With a positive count, it returns up to count distinct fields, capped by the hash size.
Follow-up: What changes for a negative count? It returns exactly the absolute count and can repeat fields.
WITHVALUES makes the response include each selected field together with its associated value. The modifier must be used with count.
Follow-up: How should a client handle the response shape? Branch on whether WITHVALUES was requested and parse field/value pairs accordingly.
A missing key behaves like an empty hash for sampling purposes. A negative count returns an empty array in that case, while a no-count request has no field to return.
Follow-up: What ordering guarantee exists? The reply order is not truly random, so shuffle it in the client if required.
HGETHGETALLHSCANHSETHRANDFIELD