ZREVRANGEBYLEX

Introduction and Use Case(s)

The ZREVRANGEBYLEX command in Redis is used to return a range of members in a sorted set, specified by a lexicographical range, in reverse order. This is particularly useful when you need to retrieve elements stored in a specific lexicographical order but starting from the highest to the lowest values.

Syntax

  1. ZREVRANGEBYLEX key max min [LIMIT offset count]

Parameter Explanations

  • key: The name of the sorted set.
  • max: The maximum value in the lexicographical range (inclusive or exclusive).
  • min: The minimum value in the lexicographical range (inclusive or exclusive).
  • LIMIT offset count: Optional argument to limit the number of elements returned with an offset.

Lexicographical range limits:

  • To specify open intervals, use parentheses (.
  • To specify closed intervals, use brackets [.
  • Special values + and - can be used for positive and negative infinity, respectively.

Return Values

Returns an array of elements in the specified reversed lexical range. If no elements are found, an empty array is returned.

Code Examples

  1. dragonfly> ZADD myzset 0 "apple" 0 "banana" 0 "cherry" 0 "date"
  2. (integer) 4
  3. dragonfly> ZREVRANGEBYLEX myzset [cherry [banana
  4. 1) "cherry"
  5. 2) "banana"
  6. dragonfly> ZREVRANGEBYLEX myzset (cherry (banana
  7. (empty array)
  8. dragonfly> ZREVRANGEBYLEX myzset + -
  9. 1) "date"
  10. 2) "cherry"
  11. 3) "banana"
  12. 4) "apple"
  13. dragonfly> ZREVRANGEBYLEX myzset [date [apple LIMIT 1 2
  14. 1) "cherry"
  15. 2) "banana"

Best Practices

  • Ensure that the sorted set is not too large when using the LIMIT option to avoid heavy memory usage.
  • Be cautious with lexicographical ranges as they can be inclusive or exclusive, impacting the results.

Common Mistakes

  • Misunderstanding the inclusive [] and exclusive () syntax for specifying the range, which can lead to unexpected results.
  • Forgetting to handle cases where the resultant set might be empty, especially in application logic.

FAQs

What happens if the key does not exist?

If the specified sorted set key does not exist, ZREVRANGEBYLEX returns an empty array.

Can ZREVRANGEBYLEX work with numeric scores?

No, ZREVRANGEBYLEX operates purely on the lexicographical ordering of the elements, not their scores.