Easy Tutorial
❮ Sorted Sets Zadd Redis Pipelining ❯

Redis Srandmember Command

Redis Sets

The Redis Srandmember command is used to return a random element from a set.

Starting from Redis 2.6, the Srandmember command accepts an optional count parameter:

This operation is similar to SPOP, but while SPOP removes and returns a random element from the set, Srandmember only returns a random element without modifying the set.

Syntax

The basic syntax of the redis Srandmember command is as follows:

redis 127.0.0.1:6379> SRANDMEMBER KEY [count]

Available Versions

= 1.0.0

Return Value

When only the set key is provided, it returns a single element; if the set is empty, it returns nil. If the count parameter is provided, it returns an array; if the set is empty, it 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 Sets

❮ Sorted Sets Zadd Redis Pipelining ❯