Anthony Kong
Anthony Kong

Reputation: 40634

Why I cannot use ZRANGEBYLEX on this sorted set in redis?

In the redis documentation, there is this example of ZRANGEBYLEX

ZADD myindex 0 0056:0028.44:90
ZADD myindex 0 0034:0011.00:832
ZRANGEBYLEX myindex [0056:0010.00 [0056:0030.00
1) "0056:0028.44:90"

It is very straightforward.

However if I want to apply the same technique to the following example,

127.0.0.1:6379> zadd feedbacks 1 feedback1 2 feedback2 3 feedback3 1 feedback4
(integer) 4
127.0.0.1:6379> ZRANGEBYLEX feedbacks [feed [feed
(empty list or set)

I get an empty set.

I would expect to see the four values (feedback1 to feedback4)

Why ZRANGEBYLEX failed on my test sample?

Upvotes: 2

Views: 921

Answers (1)

LeoMurillo
LeoMurillo

Reputation: 6754

It fails because they have different scores. ZRANGEBYLEX works only on same-score subsets.

See https://redis.io/commands/ZRANGEBYLEX

When all the elements in a sorted set are inserted with the same score, in order to force lexicographical ordering, this command returns all the elements in the sorted set at key with a value between min and max.

If the elements in the sorted set have different scores, the returned elements are unspecified.

Sorted sets have the property of being lexicographically ordered within same-score subsets. This gives them a second use-case, a lexicographically sorted set, but in this case, you add all elements with the same score.

So, you have to choose how to use your sorted set:

  • Sorted by score (with same-score sorted lex, for predictable order)
  • Sorted lexicographically, all elements given the same score

You cannot have both. You'd need two sorted sets then.

Upvotes: 4

Related Questions