本文内容为 http://redis.io/commands/zrange 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
ZRANGE key start stop [WITHSCORES]

返回储存在键 key 对应的有序集合(Sorted set)中指定范围内的元素。

Returns the specified range of elements in the sorted set stored at key.

所有元素按最低分值(Score)到最高分值排序。如果分值相同,则按字典序(Lexicographical order )排序。

The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score.

如果需要使元素按最高分值(Score)到最低分值排序(如果分值相同,则按逆字典序(Descending lexicographical order )排序),请查看 ZREVRANGE

选项 startstop 都是基于 0(Zero-based)的索引。即索引 0 代表第一个元素,1 代表下一元素,以此类推。它们也可以为负值,表明偏移从有序集合末尾开始计算,-1 为最后一个元素,-2 为倒数第二个元素,以此类推。

Both start and stop are zero-based indexes, where 0 is the first element, 1 is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with -1 being the last element of the sorted set, -2 the penultimate element and so on.

超出范围的索引将不会产生错误。

如果选项 start 比有序集合中最大索引还要大,或 start > stop,将会返回空列表。

如果选项 stop 比有序集合中最大索引还要大,Redis 将会视其为有序集合中最后一个元素对待。

Out of range indexes will not produce an error. If start is larger than the largest index in the sorted set, or start > stop, an empty list is returned. If stop is larger than the end of the sorted set Redis will treat it like it is the last element of the sorted set.

也可以通过传递 WITHSCORES 选项以达到同时返回元素分值(Score)的目的。返回的列表将会包含 value1,score1,……valueN,scoreN,而不是 value1,……valueN。客户端库可以自由的返回更加合适的数据类型(推荐:元素为(value,score)数组或二元组的数组)。

It is possible to pass the WITHSCORES option in order to return the scores of the elements together with the elements. The returned list will contain value1,score1,...,valueN,scoreN instead of value1,...,valueN. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples).
  • 指定范围中的元素列表(可包含对应的分值)。

    List of elements in the specified range (optionally with their scores).
  • redis> ZADD myzset 1 "one"
    (integer) 1
    redis> ZADD myzset 2 "two"
    (integer) 1
    redis> ZADD myzset 3 "three"
    (integer) 1
    redis> ZRANGE myzset 0 -1
    1) "one"
    2) "two"
    3) "three"
    redis> ZRANGE myzset 2 3
    1) "three"
    redis> ZRANGE myzset -2 -1
    1) "two"
    2) "three"
  • 版本支持

    1.2.0+

    时间复杂度(Time complexity)

    O(log(N)+M)N 为有序集合中元素的个数,M 为返回的元素个数。

    O(log(N)+M) with N being the number of elements in the sorted set and M the number of elements returned.