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

返回储存在键 key 对应的有序集合(Sorted set)中且分值(Socre)在最大值 max 及最小值 min 之间(包括值等于 min 或 max 的元素)的所有元素。所有元素被认为是按分值从小到大排序的。

Returns all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max).The elements are considered to be ordered from low to high scores.

相同分值的元素将以字典序(Lexicographical order)返回,该特性由 Redis 内部对有序集合的实现方式所附带,不会产生进一步计算。

The elements having the same score are returned in lexicographical order (this follows from a property of the sorted set implementation in Redis and does not involve further computation).

可选参数 LIMIT 可以用来获取所匹配元素的某个范围(类似于 SQL 语法中的 SELECT LIMIT offset,count 语句)。必须要注意的是,如果偏移 offset 很大,在获得所需返回元素之前,需要遍历有序集合以定位偏移 offset 处的元素,时间复杂度总计为 O(N)

The optional LIMIT argument can be used to only get a range of the matching elements (similar to SELECT LIMIT offset, count in SQL). Keep in mind that if offset is large, the sorted set needs to be traversed for offset elements before getting to the elements to return, which can add up to O(N) time complexity.

可选项 WITHSCORES 使得当前命令同时返回元素及对应的分值,而不是仅仅返回单个元素。该选项从 2.0 版本开始可用。

The optional WITHSCORES argument makes the command return both the element and its score, instead of the element alone. This option is available since Redis 2.0.
  • 指定范围中的元素列表(可包含对应的分值)。

    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> ZRANGEBYSCORE myzset -inf +inf
    1) "one"
    2) "two"
    3) "three"
    redis> ZRANGEBYSCORE myzset 1 2
    1) "one"
    2) "two"
    redis> ZRANGEBYSCORE myzset (1 2
    1) "two"
    redis> ZRANGEBYSCORE myzset (1 (2
    (empty list or set)
  • Exclusive intervals and infinity

    min and max can be -inf and +inf, so that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score.

    By default, the interval specified by min and max is closed (inclusive). It is possible to specify an open interval (exclusive) by prefixing the score with the character (. For example:

    ZRANGEBYSCORE zset (1 5

    Will return all elements with 1 < score <= 5 while:

    ZRANGEBYSCORE zset (5 (10

    Will return all the elements with 5 < score < 10 (5 and 10 excluded).

  • 版本支持

    1.0.5+

    时间复杂度(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 being returned. If M is constant (e.g. always asking for the first 10 elements with LIMIT), you can consider it O(log(N)).