Redis ZLEXCOUNT Command Explained

In Redis, the ZLEXCOUNT command returns the number of elements in a sorted set with a value between two given values. It can be used when we force lexicographical ordering by applying the same score to all members of a sorted set.

Syntax

The syntax goes like this:

ZLEXCOUNT key min max

The min and max arguments must start with either ( or [ to indicate whether the range is inclusive or exclusive. When it starts with the ( character, it’s exclusive, when it starts with the [ character it’s inclusive. This is demonstrated in the following examples.

Example

Suppose we create the following sorted set:

ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g

Let’s use the ZLEXCOUNT command to find out how many elements in the sorted set have a value between two values:

ZLEXCOUNT myzset [b [f

Result:

(integer) 5

In this case I used the [ argument to make it inclusive.

The integer reply of 5 tells us that there are five members with values between our range of b and f.

Inclusive vs Exclusive

In the previous example we started the min and max values with the [ character. This indicates that it’s an inclusive range. In other words, the b and the f were included when determining the result.

We can alternatively use the ( character to specify an exclusive range:

ZLEXCOUNT myzset (b (f

Result:

(integer) 3

In this case, the b and f were not included in the range (i.e. the range went from c to e).

We can make one argument inclusive while the other is exclusive:

ZLEXCOUNT myzset [b (f

Result:

(integer) 4

In that case the b was included in the calculation but the f wasn’t.

Here it is the other way around:

ZLEXCOUNT myzset (b [f

Result:

(integer) 4

Same result, but this time the b was excluded, while the f was included.

We can verify this by using the ZRANGE command to return the actual members:

ZRANGE myzset (b [f BYLEX

Result:

1) "c"
2) "d"
3) "e"
4) "f"

As expected, b was excluded, while the f was included.

Include All Members

We can use the special values of + or - to specify all members in the sorted set (assuming they all have the same score). These characters indicate the positively infinite and negatively infinite strings respectively.

Example:

ZLEXCOUNT myzset - +

Result:

(integer) 7

If you find that it returns zero, but you think that’s wrong, check that you’ve got them around the right way:

ZLEXCOUNT myzset + -

Result:

(integer) 0

Here, I used + - instead of + - and so no elements were included.