Redis ZREVRANGEBYSCORE – How to get elements of sorted set by score range and in desc order

5 days ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get all the elements of the sorted set value having score between specific range and in descending order by score. For this we will use redis ZREVRANGEBYSCORE command.

ZREVRANGEBYSCORE Command

This command returns all the elements of the sorted set value, whose score is less than equal to max ( inclusive ) score and greater than equal to min ( inclusive ) score passed as an argument. Here elements are returned in descending order by score and for elements having equal score, they are arranged in descending lexicographical order.

By default max and min arguments are closed interval (inclusive) but it is possible to specify them as open interval (exclusive) by prefixing them with ( character. For example :- 

ZREVRANGEBYSCORE set (5 1 

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

ZREVRANGEBYSCORE zset (10 (5

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

max and min argument can be +inf (positive infinity) and -inf (negative infinity), 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 range.

Optional Arguments

The Redis ZREVRANGEBYSCORE command takes following optional arguments :-

  1. WITHSCORES :- It returns score of the element together with the element. In this case, returned array will contain value1, score1, …. valueN, scoreN instead of value1, …., valueN.
  2. LIMIT :- It returns the count matching elements starting from the offset. If count value is negative then all elements are returned from the offset.

An empty set is returned, if key does not exist and error is returned, if key exist but value stored at the key is not of sorted set datatype. The syntax of redis ZREVRANGEBYSCORE command is as follows :- 

Syntax :-

redis host:post> ZREVRANGEBYSCORE <keyname> <max> <min> [WITHSCORES] [LIMIT offset count]

Output :-

- (array) reply, representing elements of the sorted set in the specified range.
- Empty Set, if key does not exists.
- Error, if key exist and value stored at the key is not a sorted set.

Example :-

Redis ZREVRANGEBYSCORE

References :-

  1. ZREVRANGEBYSCORE Command Docs

That’s all for how to get all the elements of the sorted set value having score between specific range and in descending order by score, stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.