ZRANDMEMBER

Syntax
ZRANDMEMBER key [count [WITHSCORES]]
Available since:
6.2.0
Time complexity:
O(N) where N is the number of members returned
ACL categories:
@read, @sortedset, @slow,

当仅使用key参数调用时,从存储在key的排序集合值中返回一个随机元素。

如果提供的 count 参数为正数,则返回一个包含不同元素的数组。 数组的长度是 count 或有序集合的基数(ZCARD)中的较小者。

如果使用负数的count调用,行为会发生变化,命令允许返回相同的元素多次。 在这种情况下,返回的元素数量是指定count的绝对值。

可选的 WITHSCORES 修饰符会改变回复,使其包括从排序集合中随机选择的元素的相应分数。

示例

ZADD dadi 1 uno 2 due 3 tre 4 quattro 5 cinque 6 sei ZRANDMEMBER dadi ZRANDMEMBER dadi ZRANDMEMBER dadi -5 WITHSCORES

当传递count时的行为规范

count参数为正值时,此命令的行为如下:

  • 不返回重复的元素。
  • 如果 count 大于有序集合的基数,命令将只返回整个有序集合,不会包含额外的元素。
  • 回复中元素的顺序并不是真正随机的,因此如果需要,客户端需要自行打乱它们。

count为负值时,行为变化如下:

  • 可以重复元素。
  • 总是返回count个元素,如果排序集合为空(不存在的键),则返回一个空数组。
  • 回复中元素的顺序是真正随机的。

RESP2 回复

Bulk string reply: without the additional count argument, the command returns a randomly selected member, or Nil reply when key doesn't exist. Array reply: when the additional count argument is passed, the command returns an array of members, or an empty array when key doesn't exist. If the WITHSCORES modifier is used, the reply is a list of members and their scores from the sorted set.

RESP3 回复

Bulk string reply: without the additional count argument, the command returns a randomly selected member, or Null reply when key doesn't exist. Array reply: when the additional count argument is passed, the command returns an array of members, or an empty array when key doesn't exist. If the WITHSCORES modifier is used, the reply is a list of members and their scores from the sorted set.
RATE THIS PAGE
Back to top ↑