Redis ZREVRANGE – How to get multiple elements of sorted set in Desc order
4 weeks ago Lalit Bhagtani 0
In this tutorial, we will learn about how to get one or more elements of the sorted set value in descending order by score, stored at a key in redis datastore, by using redis ZREVRANGE commands.
The ZREVRANGE command, returns one or more elements of the sorted set value stored at specified key, defined by the specified range. The elements in the sorted set are in descending order by score. Descending lexicographical order is used for the elements with equal score.
Range is defined by the start ( inclusive ) and end ( inclusive ) offsets, these offsets are zero based indexes where 0 means the first element, 1 means the second element and so on. Negative numbers can also be used to provide an offset starting from the end of the list value, here -1 means the last element, -2 means second last element and so on.
An out of range offsets are handle in the following ways :-
- ( start > end ) or ( start > size of sorted set ) :- Result is an empty list.
- ( end > size of sorted set ) :- Index of last element of the sorted set value is set to end 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 WITHSCORES ( optional ) argument can be passed in the command, to get the scores of the elements together with the elements. In this case, returned array will contain value1, score1, …. valueN, scoreN instead of value1, …., valueN.
The syntax of redis ZREVRANGE command is as follows :-
redis host:post> ZREVRANGE <keyname> <start> <stop> [ WITHSCORES ]
- (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.
That’s all for how to get one or more elements of the sorted set value in descending order by score in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.