0
0
RedisHow-ToBeginner · 3 min read

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 at key.
  • SRANDMEMBER key count: Returns count random members from the set. If count is 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 key to remove the member; it only returns it without removal.
  • Using a positive count larger than the set size returns all members without duplicates, not an error.
  • Using a negative count can return duplicates, which might be unexpected.
redis
/* Wrong: expecting removal */
SRANDMEMBER fruits
SMEMBERS fruits

/* Right: use SPOP to remove */
SPOP fruits
📊

Quick Reference

CommandDescription
SRANDMEMBER keyReturn one random member from the set
SRANDMEMBER key countReturn count random members, unique if count > 0
SRANDMEMBER key -countReturn count random members, duplicates allowed
SPOP keyRemove 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.