Redis Srandmember Command
The Redis Srandmember command is used to return a random element from the set.
Starting from Redis 2.6, the Srandmember command accepts an optional count parameter:
- If count is positive and less than the set cardinality, the command returns an array containing count elements, each different. If count is greater than or equal to the set cardinality, the entire set is returned.
- If count is negative, the command returns an array in which elements may appear repeatedly, and the length of the array is the absolute value of count.
This operation is similar to SPOP, but SPOP removes the random element from the set and returns it, while Srandmember only returns the random element without making any changes to the set.
Syntax
The basic syntax of the redis Srandmember command is as follows:
redis 127.0.0.1:6379> SRANDMEMBER KEY [count]
Available Version
= 1.0.0
Return Value
When only the set key parameter is provided, returns one element; if the set is empty, returns nil. If the count parameter is provided, returns an array; if the set is empty, returns an empty array.
Example
redis 127.0.0.1:6379> SADD myset1 "hello"
(integer) 1
redis 127.0.0.1:6379> SADD myset1 "world"
(integer) 1
redis 127.0.0.1:6379> SADD myset1 "bar"
(integer) 1
redis 127.0.0.1:6379> SRANDMEMBER myset1
"bar"
redis 127.0.0.1:6379> SRANDMEMBER myset1 2
1) "Hello"
2) "world"
Redis Set