Redis ZRANGE – How to get multiple elements of sorted set in Asc 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 ascending order by score, stored at a key in redis datastore, by using redis ZRANGE commands.

ZRANGE Command

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 :-

  1. ( start > end ) or ( start > size of sorted set ) :- Result is an empty list.
  2. ( 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 :- 

Syntax :-

redis host:post> ZRANGE <keyname> <start> <stop> [ WITHSCORES ]

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 ZRANGE

References :-

  1. ZRANGE Command Docs

That’s all for how to get one or more elements of the sorted set value in ascending order by score in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.