Redis ZLEXCOUNT – How to get number of elements in sorted set by value range

6 days ago Lalit Bhagtani 0

In this tutorial, we will learn about how to get the number of elements of the sorted set value having values between a specific range. For this, we will use Redis ZLEXCOUNT command.

ZLEXCOUNT Command

This command returns the number of elements of the sorted set value, whose values (string representation of element) are between min and max arguments. Here all the elements in a sorted set value are inserted with the same score, in order to force lexicographical ordering.

The min and max arguments must start with ( or [, where [ specifies closed interval (inclusive) and ( specifies open interval (exclusive). For example :- 

ZLEXCOUNT set [a [f

Will return number of elements with a <= element <= f while:

ZLEXCOUNT set [a (f

Will return number of elements with <= element < f

The min and max arguments can have special values of + or , where + specifies positive infinite strings and specifies negative infinite strings, so for example the command ZLEXCOUNT set – + will return the size of the sorted set value.

The error is returned, if a key exists but value stored at the key is not of sorted set datatype. The syntax of Redis ZLEXCOUNT command is as follows:- 

Syntax :-

redis host:post> ZLEXCOUNT <keyname> <min> <max>

Output :-

- (array) reply, representing number of elements in the specified range.
- Error, if key exist and value stored at the key is not a sorted set.

Example :-

Redis ZLEXCOUNT

References :-

  1. ZLEXCOUNT Command Docs

That’s all for how to get the number of elements of the sorted set value having values between a specific range. If you liked it, please share your thoughts in comments section and share it with others too.