Redis Sets: SRANDMEMBER
Redis SRANDMEMBER Command
Redis SRANDMEMBER command is used to return a random element from the set value stored at key when called with just the key argument. When called with the additional count argument, return an array of count distinct elements if positive and if called with a negative, 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.
Here are some common uses and scenarios for the "SRANDMEMBER" command:
- Random Sampling: Retrieves one or more random members from a set without removing them.
- Load Testing: Useful for generating random test data or sampling data from a set.
- Non-Destructive Random Access: Allows random access to set elements without modifying the set.
- Random Selection: Helps in scenarios where a random choice or selection is needed from a predefined set of options.
Syntax:
SRANDMEMBER KEY [count]
Available since:
1.0.0.
Return Value:
String reply, without the additional count argument the command returns a Bulk Reply with the randomly selected element, or nil when the key does not exist. Array reply, when the additional count argument is passed the command returns an array of elements, or an empty array when the key does not exist.
Return Value Type:
String
Example: Redis SRANDMEMBER : Views random member from the set
127.0.0.1:6379> SADD mycolor "red" "green" "blue" "yellow" (integer) 4 127.0.0.1:6379> SRANDMEMBER mycolor "blue" 127.0.0.1:6379> SRANDMEMBER mycolor "yellow"
Example: Redis SRANDMEMBER : Counting
If the count is positive, the inquiry does not duplicate the member.
If the count is negative, it may be queried to duplicate the member.
127.0.0.1:6379> SRANDMEMBER mycolor 3 1) "red" 2) "green" 3) "yellow" 127.0.0.1:6379> SRANDMEMBER mycolor -3 1) "green" 2) "blue" 3) "yellow"
Example: Redis SRANDMEMBER : If the count is greater than the member
If the count is positive, the number of queries by the member.
If the count is negative, it will be viewed as duplicate member count.
127.0.0.1:6379> SRANDMEMBER mycolor 6 1) "red" 2) "green" 3) "yellow" 4) "blue" 127.0.0.1:6379> SRANDMEMBER mycolor -6 1) "blue" 2) "red" 3) "red" 4) "blue" 5) "blue" 6) "red"
Previous:
Redis Sets SPOP
Next:
Redis Sets SREM
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics