Redis ZSCORE Command Explained

In Redis, the ZSCORE command returns the score of the specified member of a sorted set.

Syntax

The syntax goes like this:

ZSCORE key member

Example

Suppose we create a sorted set like this:

ZADD cats 15 Meow 27 Fluffy 43 Scratch 84 Purr 25 Bite 37 Bunting

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 ZSCORE command to find out the score of a given member:

ZSCORE cats Scratch

Result:

"43"

The member has a score of 43 as expected.

Let’s try another member:

ZSCORE cats Meow

Result:

"15"

As expected.

When the Member or Key Doesn’t Exist

If the member doesn’t exist we get nil:

ZSCORE cats Fur

Result:

(nil)

Same when the key doesn’t exist:

ZSCORE dogs Meow

Result:

(nil)

We can use the EXISTS command to check for the existence of a key:

EXISTS dogs

Result:

(integer) 0

An integer reply of zero means that it doesn’t exist.

Wrong Type

If the key contains the wrong data type, an error occurs:

ZSCORE animals Bite

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In my case, the animals key contains a set (not a sorted set) and so we get the error.

We can use the TYPE command to check the key’s data type:

TYPE animals

Result:

set

As suspected, it’s a set.