0
0
Redisquery~5 mins

SRANDMEMBER for random elements in Redis

Choose your learning style9 modes available
Introduction
SRANDMEMBER helps you pick one or more random items from a set stored in Redis without removing them.
When you want to show a random quote from a list of quotes.
When you need to pick a random user from a set of online users.
When you want to select a random prize from a list of prizes.
When you want to test or sample random data from a stored collection.
Syntax
Redis
SRANDMEMBER key [count]
If you do not provide count, it returns one random element.
If count is positive, it returns up to count unique random elements.
If count is negative, it can return repeated elements.
Examples
Returns one random element from the set 'myset'.
Redis
SRANDMEMBER myset
Returns up to 3 unique random elements from 'myset'.
Redis
SRANDMEMBER myset 3
Returns 2 random elements from 'myset', elements may repeat.
Redis
SRANDMEMBER myset -2
Sample Program
First, we add four fruits to the set 'fruits'. Then we get one random fruit, then two unique random fruits, then three random fruits allowing repeats.
Redis
SADD fruits apple banana cherry date
SRANDMEMBER fruits
SRANDMEMBER fruits 2
SRANDMEMBER fruits -3
OutputSuccess
Important Notes
SRANDMEMBER works only on sets, not lists or other data types.
Using a negative count can return repeated elements, which is useful if you want random picks with replacement.
If the count is larger than the set size and positive, it returns all elements without repeats.
Summary
SRANDMEMBER picks random elements from a Redis set without removing them.
You can get one element or multiple unique or repeated elements by using the count parameter.
It is useful for random sampling or selection tasks in Redis.