HRANDFIELD command is used to randomly select one or more fields from a hash stored in Redis. This is useful in scenarios where you need a random sample from a dataset, such as displaying random user profiles, selecting random items, or for any feature that requires a random element from a collection.
This example retrieves a single random field name from the hash 'user:100'. The
hrandfield method returns a promise resolving to the random field name.
In this second example,
hrandfield is used to retrieve three random fields along with their values from the hash 'user:100'. By specifying the count and the
WITHVALUES option, the returned result is an array of field-value pairs.
hrandfield, be aware of the size of the hash since fetching a large number of fields can be resource-intensive. Also, consider the randomness requirements of your application;
HRANDFIELD provides non-deterministic results but does not guarantee a uniform distribution.
WITHVALUESoption, only field names are returned, not their corresponding values.
Q: What happens if I use
HRANDFIELD on a non-existent key?
A: Redis will return
nil if the key does not exist.
HRANDFIELD return the same field multiple times if a count greater than 1 is specified?
A: No, every field returned will be unique unless the count exceeds the number of fields present in the hash. If the count is greater than the number of fields in the hash and
ALLOWDUPLICATES is specified, fields may be repeated in the result.