Redis ZRANK Command Explained

In Redis, the ZRANK command returns the rank of the specified element of a sorted set.

The scores are ordered from low to high. If we want them in the opposite order, we can use the ZREVRANK command.

Syntax

The syntax goes like this:

ZRANK key member

Example

Suppose we create a sorted set like this:

ZADD scores 220 user:1 110 user:2 330 user:3 550 user:4 440 user:5 660 user:6

Result:

(integer) 6

In my case the sorted set didn’t exist, and so it was created and the six elements were added as specified.

Let’s now use the ZRANK command to find out the rank of a given member:

ZRANK scores user:3

Result:

(integer) 2

In this case, the element has a rank of 2. The rank is zero based, and so this element is ranked third.

Let’s try another element:

ZRANK scores user:2

Result:

(integer) 0

This element has the lowest rank, and so we get zero.

When the Element or Key Doesn’t Exist

If the element doesn’t exist we get nil:

ZRANK scores user:10

Result:

(nil)

Same when the key doesn’t exist:

ZRANK oops user:10

Result:

(nil)