redis Sorted Sets Counting Items in a Sorted Set


Redis provides three commands to count the items within a sorted set: ZCARD, ZCOUNT, ZLEXCOUNT.

The ZCARD command is the basic test for the cardinality of a set. (It is analogous to the SCARD command for sets.) . ZCARD returns the count of the members of a set. Executing the following code to add items to a set:

zadd favs 1 apple
zadd favs 2 pizza
zadd favs 3 chocolate
zadd favs 4 beer

running ZCard:

zcard favs

returns a value of 4.

The ZCOUNT and ZLEXCOUNT commands allow you to count a subset of the items in a sorted set based on a range of values. ZCOUNT allows you to count items within a particular range of scores and ZLEXCOUNT allowes you to count the number of items within a particular lexographic range.

Using our set above:

zcount favs 2 5

would return a 3, since there are three items (pizza, chocolate, beer) that have scores between 2 and 5 inclusive.

ZLEXCOUNT is designed to work with sets where every item has the same score, forcing and ordering on the elemement names. If we created a set like:

zadd favs 1 apple
zadd favs 1 pizza
zadd favs 1 chocolate
zadd favs 1 beer

we could use ZLEXCOUNT to get the number of elements in particular lexographical range (this is done by byte-wise comparison using the memcpy function).

zlexcount favs [apple (chocolate

would return 2, since two elements (apple, beer) fall within the range apple (inclusive) and chocolate (exclusive). We could alternatively make both ends inclusive:

zlexcount favs [apple [chocolate

and get the result 3.