Redis ZRANGE – How to get elements of sorted set by Asc Rank Range
2 months ago Lalit Bhagtani 0
In this tutorial, we will learn about how to get one or more elements of the sorted set value having rank between specific range and in ascending order by score. For this, we will use Redis ZRANGE commands.
The ZRANGE 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 ascending order by score. Ascending 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 ZRANGE command is as follows :-
redis host:post> ZRANGE <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 having rank between specific range and in ascending order by score. If you liked it, please share your thoughts in comments section and share it with others too.