ZRANDMEMBER
ZRANDMEMBER key [count [WITHSCORES]]
- Available since:
- Redis Open Source 6.2.0
- Time complexity:
- O(N) where N is the number of members returned
- ACL categories:
-
@read,@sortedset,@slow, - Compatibility:
- Redis Software and Redis Cloud compatibility
When called with just the key argument, return a random element from the sorted 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 sorted set's cardinality (ZCARD), 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.
The optional WITHSCORES modifier changes the reply so it includes the respective scores of the randomly selected elements from the sorted set.
Required arguments
key
The name of the key that holds the sorted set.
Optional arguments
count
The number of members to return. A positive count returns up to that many distinct members; a negative count returns exactly |count| members and may repeat them.
WITHSCORES
Also return the score of each returned member. Can only be used together with count.
Examples
Details
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
countis bigger than the cardinality of the sorted set, the command will only return the whole sorted 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
countelements, or an empty array if the sorted set is empty (non-existing key), are always returned. - The order of elements in the reply is truly random.
Redis Software and Redis Cloud compatibility
| Redis Software |
Redis Cloud |
Notes |
|---|---|---|
| ✅ Standard |
✅ Standard |