In Redis, the ZCARD
command returns the cardinality (number of elements) of a sorted set.
Syntax
The syntax goes like this:
ZCARD key
Example
Suppose we create a sorted set like this:
ZADD scores 220 user:1 110 user:2 330 user:3 550 user:4
Result:
(integer) 4
In my case the sorted set didn’t exist, and so it was created and the four elements were added as specified.
We can now use the ZCARD
command to find out how many elements are in the sorted set:
ZCARD scores
Result:
(integer) 4
As expected, there are four elements in the sorted set.
Let’s add two more elements:
ZADD scores 440 user:5 660 user:6
Result:
(integer) 2
And now let’s run ZCARD
again:
ZCARD scores
Result:
(integer) 6
Now there are six elements in the sorted set.
When the Key Doesn’t Exist
If the key doesn’t exist, ZCARD
returns zero:
ZCARD nonexistentkey
Result:
(integer) 0
In this case, nonexistentkey
doesn’t exist and so the command returned zero.