How to Use SRANDMEMBER in Redis: Syntax and Examples
Use the
SRANDMEMBER command in Redis to get one or more random members from a set without removing them. You can specify the number of random members to return by adding a count argument, which can be positive or negative to control uniqueness.Syntax
The SRANDMEMBER command syntax is:
SRANDMEMBER key: Returns one random member from the set stored atkey.SRANDMEMBER key count: Returnscountrandom members from the set. Ifcountis positive, members are unique. If negative, members may repeat.
redis
SRANDMEMBER key [count]
Example
This example shows how to get random members from a Redis set named fruits.
redis
SADD fruits apple banana cherry date SRANDMEMBER fruits SRANDMEMBER fruits 2 SRANDMEMBER fruits -3
Output
1) "banana"
1) "apple"
2) "date"
1) "cherry"
2) "banana"
3) "banana"
Common Pitfalls
Common mistakes when using SRANDMEMBER include:
- Expecting
SRANDMEMBER keyto remove the member; it only returns it without removal. - Using a positive
countlarger than the set size returns all members without duplicates, not an error. - Using a negative
countcan return duplicates, which might be unexpected.
redis
/* Wrong: expecting removal */ SRANDMEMBER fruits SMEMBERS fruits /* Right: use SPOP to remove */ SPOP fruits
Quick Reference
| Command | Description |
|---|---|
| SRANDMEMBER key | Return one random member from the set |
| SRANDMEMBER key count | Return count random members, unique if count > 0 |
| SRANDMEMBER key -count | Return count random members, duplicates allowed |
| SPOP key | Remove and return a random member from the set |
Key Takeaways
SRANDMEMBER returns random members from a set without removing them.
Specify count to get multiple members; positive count means unique members.
Negative count allows duplicates in the returned members.
Use SPOP if you want to remove random members from the set.
If count is larger than set size and positive, all members are returned without duplicates.