SRANDMEMBER · Valkey

SRANDMEMBER

Get one or multiple random members from a set

Usage

SRANDMEMBER key [count]

Description

When called with just the key argument, return a random element from the set value stored at key.

If the provided count argument is positive, return an array of distinct elements. The array’s length is either count or the set’s cardinality (SCARD), whichever is lower.

If called with a negative count, the behavior changes and the command is allowed to return the same element multiple times. In this case, the number of returned elements is the absolute value of the specified count.

Reply RESP2

One of the following:

Reply RESP3

One of the following:

Complexity

Without the count argument O(1), otherwise O(N) where N is the absolute value of the passed count.

ACL Categories

@read @set @slow

Examples

127.0.0.1:6379> SADD myset one two three
(integer) 3
127.0.0.1:6379> SRANDMEMBER myset
"three"
127.0.0.1:6379> SRANDMEMBER myset 2
1) "one"
2) "three"
127.0.0.1:6379> SRANDMEMBER myset -5
1) "two"
2) "one"
3) "one"
4) "one"
5) "two"

Specification of the behavior when count is passed

When the count argument is a positive value this command behaves as follows:

When the count is a negative value, the behavior changes as follows:

History

See also

SADD, SCARD, SDIFF, SDIFFSTORE, SINTER, SINTERCARD, SINTERSTORE, SISMEMBER, SMEMBERS, SMISMEMBER, SMOVE, SPOP, SREM, SSCAN, SUNION, SUNIONSTORE.