redis SRANDMEMBER command


  Translation results:

rand

英[rænd] 美[rænd]

n. The padding between the heel of the shoe and the sole, edge

plural : rands rand

member

UK[ˈmembə(r)] US[ˈmɛmbɚ]

n. Member; molecule; body part (especially arm or leg); member, part

plural: members

redis SRANDMEMBER commandsyntax

Function: If only the key parameter is provided when the command is executed, a random element in the collection will be returned.

Syntax: SRANDMEMBER key [count]

Description: Starting from Redis version 2.6, the SRANDMEMBER command accepts the optional count parameter: if count is a positive number and less than the cardinality of the collection, then the command returns an array containing count elements, and the elements in the array are different. If count is greater than or equal to the collection cardinality, then the entire collection is returned. If count is negative, the command returns an array, the elements of which may appear multiple times, and the length of the array is the absolute value of count . This operation is similar to SPOP, but SPOP removes random elements from the collection and returns it, while SRANDMEMBER only returns random elements without making any changes to the collection.

Available versions: >= 1.0.0

Time complexity: O(1) when only key parameter is provided. If the count parameter is provided, it is O(N), where N is the number of elements in the returned array.

Return: When only the key parameter is provided, an element is returned; if the collection is empty, nil is returned. If the count parameter is provided, an array is returned; if the collection is empty, an empty array is returned.

redis SRANDMEMBER commandexample

# 添加元素
redis> SADD fruit apple banana cherry
(integer) 3
# 只给定 key 参数,返回一个随机元素
redis> SRANDMEMBER fruit
"cherry"
redis> SRANDMEMBER fruit
"apple"
# 给定 3 为 count 参数,返回 3 个随机元素
# 每个随机元素都不相同
redis> SRANDMEMBER fruit 3
1) "apple"
2) "banana"
3) "cherry"
# 给定 -3 为 count 参数,返回 3 个随机元素
# 元素可能会重复出现多次
redis> SRANDMEMBER fruit -3
1) "banana"
2) "cherry"
3) "apple"
redis> SRANDMEMBER fruit -3
1) "apple"
2) "apple"
3) "cherry"
# 如果 count 是整数,且大于等于集合基数,那么返回整个集合
redis> SRANDMEMBER fruit 10
1) "apple"
2) "banana"
3) "cherry"
# 如果 count 是负数,且 count 的绝对值大于集合的基数
# 那么返回的数组的长度为 count 的绝对值
redis> SRANDMEMBER fruit -10
1) "banana"
2) "apple"
3) "banana"
4) "cherry"
5) "apple"
6) "apple"
7) "cherry"
8) "apple"
9) "apple"
10) "banana"
# SRANDMEMBER 并不会修改集合内容
redis> SMEMBERS fruit
1) "apple"
2) "cherry"
3) "banana"
# 集合为空时返回 nil 或者空数组
redis> SRANDMEMBER not-exists
(nil)
redis> SRANDMEMBER not-eixsts 10
(empty list or set)

Home

Videos

Q&A