Redis ZREVRANGEBYLEX – How to get elements of sorted set by desc value range
6 days ago Lalit Bhagtani 0
In this tutorial, we will learn about how to get all the elements of the sorted set value having values between a specific range and in descending lexicographical order. For this, we will use Redis ZREVRANGEBYLEX command.
This command returns all the elements of the sorted set value stored at a specified key, with values (string representation of element) between max and min arguments. Here all the elements in a sorted set value are inserted with the same score, in order to force lexicographical ordering. Returned elements are in descending lexicographical order.
The max and min arguments must start with ( or [, where [ specifies closed interval (inclusive) and ( specifies open interval (exclusive). For example :-
ZREVRANGEBYLEX set [f [a
Will return all elements with f >= element >= a while:
ZREVRANGEBYLEX set [f (a
Will return all the elements with f >= element > a
The max and min arguments can have special values of + or –, where + specifies positive infinite strings and – specifies negative infinite strings, so for example the command ZREVRANGEBYLEX set + – will return all the elements of the sorted set value.
The LIMIT ( optional ) argument can be passed in the command, to get the count matching elements starting from the offset. If count value is negative then all elements are returned from the offset. For example:-
ZREVRANGEBYLEX set [f [a LIMIT 1 3 Where set = [a, b, c, d, e, f, g, h]
Will return three matching elements, starting from second matching element. i.e [e, d, c]
An empty set is returned, if a key does not exist and an error is returned, if a key exists but value stored at the key is not of sorted set datatype. The syntax of Redis ZREVRANGEBYLEX command is as follows:-
redis host:post> ZREVRANGEBYLEX <keyname> <max> <min> [LIMIT offset count]
- (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 all the elements of the sorted set value having values between specific range and in descending lexicographical order. If you liked it, please share your thoughts in comments section and share it with others too.