Redis SRANDMEMBER Command Explained

In Redis, the SRANDMEMBER command returns one or more random members from the set value store at the specified key.

If you want to remove the random member/s from the set, use the SPOP command.

Syntax

The syntax for SRANDMEMBER goes like this:

SRANDMEMBER key [count]

By default, only one member is returned. The optional count argument can be used to return more than one member.

Example

Suppose we create the following set:

SADD animals Cat Dog Cow Horse Bird Zebra

First, let’s use SMEMBERS to see all the members of the set:

SMEMBERS animals

Result:

1) "Dog"
2) "Cow"
3) "Cat"
4) "Horse"
5) "Zebra"
6) "Bird"

Now let’s use the SRANDMEMBER command to return a random member from that set:

SRANDMEMBER animals

Result:

"Zebra"

OK, so let’s run it again:

SRANDMEMBER animals

Result:

"Dog"

Return Multiple Members

As mentioned, we can return multiple random members from the set. To do this, we need to provide an optional second argument to specify the number of members to return:

SRANDMEMBER animals 3

Result:

1) "Horse"
2) "Dog"
3) "Bird"

This time three random members were returned.

By default, the command returns distinct members, but we can change that by passing a negative count value (see below).

Return Non-Distinct Members

Passing a negative count value enables us to get non-distinct members from the set. When we do this, the number of members returned is the absolute value of the negative value.

Example:

SRANDMEMBER animals -3

Result:

1) "Bird"
2) "Horse"
3) "Horse"

However, just because we provide a negative value doesn’t necessarily mean that the result will always contain non-distinct values. For example, here’s what happens when I run the command again:

SRANDMEMBER animals -3

Result:

1) "Dog"
2) "Horse"
3) "Bird"

This time the command returned distinct members.

Return All Members

Passing a count argument that exceeds the set’s cardinality results in all members being returned:

SRANDMEMBER animals 20

Result:

1) "Horse"
2) "Dog"
3) "Cat"
4) "Cow"
5) "Zebra"
6) "Bird"

Passing Too Many Arguments

Passing the wrong number of arguments results in an error. At the time of writing, SRANDMEMBER accepts up to two arguments. Any more results in an error:

SRANDMEMBER animals 2 3

Result:

(error) ERR syntax error

Passing No Arguments

Calling SRANDMEMBER without passing any arguments also results in an error:

SRANDMEMBER

Result:

(error) ERR wrong number of arguments for 'srandmember' command

Member Order

When passing a positive count value, the order of elements in the reply is not truly random.

When passing a negative count value, the order of elements in the reply is truly random.