srandmember.3valkey - Man Page

Get one or multiple random members from a set

Synopsis

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:

  • valkey-protocol(7) Bulk string reply: without the additional count argument, the command returns a randomly selected member, or a valkey-protocol(7) Nil reply when key doesn’t exist.
  • valkey-protocol(7) Array reply: when the optional count argument is passed, the command returns an array of members, or an empty array when key doesn’t exist.

Resp3

One of the following:

  • valkey-protocol(7) Bulk string reply: without the additional count argument, the command returns a randomly selected member, or a valkey-protocol(7) Null reply when key doesn’t exist.
  • valkey-protocol(7) Array reply: when the optional count argument is passed, the command returns an array of members, or an empty array when key doesn’t exist.

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

History

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:

  • No repeated elements are returned.
  • If count is bigger than the set’s cardinality, the command will only return the whole set without additional elements.
  • The order of elements in the reply is not truly random, so it is up to the client to shuffle them if needed.

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

  • Repeating elements are possible.
  • Exactly count elements, or an empty array if the set is empty (non-existing key), are always returned.
  • The order of elements in the reply is truly random.

See Also

sadd(3valkey), scard(3valkey), sdiff(3valkey), sdiffstore(3valkey), sinter(3valkey), sintercard(3valkey), sinterstore(3valkey), sismember(3valkey), smembers(3valkey), smismember(3valkey), smove(3valkey), spop(3valkey), srem(3valkey), sscan(3valkey), sunion(3valkey), sunionstore(3valkey)

Info

2024-09-23 8.0.0 Valkey Command Manual