Redis ZCOUNT – How to get No. of elements of sorted set by score range

5 years ago Lalit Bhagtani 0

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

ZCOUNT Command

This command returns the number of elements of the sorted set value, whose score is greater than equal to min ( inclusive ) score and less than equal to max ( inclusive ) score passed as an argument.

By default min and max arguments are closed interval (inclusive) but it is possible to specify them as the open interval (exclusive) by prefixing them with ( character. For example :- 

ZCOUNT zset (1 5 

Will return number of elements with 1 < score <= 5 while:

ZCOUNT zset (5 (10

Will return number of elements with 5 < score < 10 (5 and 10 excluded).

min and max argument can be -inf (negative infinity) and +inf (positive infinity) so that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score range.

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

Syntax :-

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

Output :- 

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

Example :-

Redis ZCOUNT

References :-

  1. ZCOUNT Command Docs

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