How to Allow Duplicate Fields when using HRANDFIELD in Redis

By default, Redis’s HRANDFIELD command returns distinct fields. In other words, it won’t return the same field multiple times – each field that’s returned by the command will only be returned once.

However, we can override this behaviour by using an negative count value for the count argument.

When we pass a negative count argument, the HRANDFIELD command allows non-distinct fields to be returned.

Example

Suppose we create the following hash:

HSET pet name "Wag" color "Brown" age 37 weight 10 height 59

Result:

(integer) 5

We created a hash with five fields.

If we were to run HRANDFIELD against that hash using a positive count value, it would return only distinct fields from that hash.

Here’s an example of what I mean:

HRANDFIELD pet 4

Result:

1) "color"
2) "height"
3) "age"
4) "weight"

Only distinct fields are returned when using a positive value.

But if we use a negative value, we can return the same field multiple times.

Example:

HRANDFIELD pet -4

Result:

1) "name"
2) "name"
3) "age"
4) "color"

In this case, the name field is returned twice.

Let’s run it again:

HRANDFIELD pet -4

Result:

1) "color"
2) "name"
3) "color"
4) "height"

Bear in mind, just because it can return duplicate fields, doesn’t mean it always will:

HRANDFIELD pet -4

Result:

1) "height"
2) "age"
3) "name"
4) "weight"

This time the fields are distinct.

We can also use a value that’s larger than the number of fields in the hash to return an array of values that’s greater than the number of fields in the hash:

HRANDFIELD pet -10

Result:

 1) "name"
 2) "height"
 3) "age"
 4) "color"
 5) "height"
 6) "weight"
 7) "weight"
 8) "name"
 9) "color"
10) "weight"