Redis provides us with two commands that allow us to get one or more random members from a given set – SRANDMEMBER
and SPOP
.
Actually, the commands are slightly different in that one deletes the random member whereas the other doesn’t, and so the command you choose will depend on whether or not you want to delete the random member at the same time.
The SRANDMEMBER
Command
The SRANDMEMBER
command returns one or more random members from a specified set. It doesn’t delete the member/s like SPOP
does.
Suppose we have the following set:
SMEMBERS animals
Result:
1) "Horse" 2) "Dog" 3) "Cat" 4) "Cow" 5) "Bird" 6) "Zebra"
We can use SRANDMEMBER
to return a random member from that set:
SRANDMEMBER animals
Result:
"Zebra"
And when we run it again, another random member is returned:
SRANDMEMBER animals
Result:
"Dog"
We can also pass a second argument to specify how many random members to return:
SRANDMEMBER animals 3
Result:
1) "Horse" 2) "Dog" 3) "Bird"
By default, SRANDMEMBER
returns distinct values, but we can also pass a negative count value to return 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"
This doesn’t mean that it will always return distinct values, but the negative count value ensures that non-distinct values can be returned.
The SPOP
Command
The SPOP
command returns one or more random members from a specified set, and deletes those members.
Here’s an example:
SPOP animals
Result:
"Horse"
Now if we check the contents of the animals set, we’ll see that it no longer contains Horse
:
SMEMBERS animals
Result:
1) "Cow" 2) "Cat" 3) "Bird" 4) "Dog" 5) "Zebra"
We can pass a count argument to determine how many random members are removed and returned:
SPOP animals 2
Result:
1) "Cow" 2) "Dog"
Now when we check the set’s contents, we see that it no longer contains those two members:
SMEMBERS animals
Result:
1) "Cat" 2) "Bird" 3) "Zebra"