How to Use ZSCORE in Redis: Syntax and Examples
Use the
ZSCORE command in Redis to get the score of a specific member in a sorted set. The syntax is ZSCORE key member, which returns the score as a string or null if the member does not exist.Syntax
The ZSCORE command retrieves the score associated with a member in a sorted set.
- key: The name of the sorted set.
- member: The member whose score you want to find.
If the member exists, it returns the score as a string. If not, it returns null.
redis
ZSCORE key member
Example
This example shows how to add members with scores to a sorted set and then retrieve the score of a specific member using ZSCORE.
redis
127.0.0.1:6379> ZADD leaderboard 100 "Alice" (integer) 1 127.0.0.1:6379> ZADD leaderboard 200 "Bob" (integer) 1 127.0.0.1:6379> ZSCORE leaderboard "Alice" "100" 127.0.0.1:6379> ZSCORE leaderboard "Charlie" (nil)
Output
"100"
(nil)
Common Pitfalls
Common mistakes when using ZSCORE include:
- Using the wrong key type (the key must be a sorted set).
- Requesting the score of a member that does not exist, which returns
null. - Confusing
ZSCOREwith commands that return ranges or multiple members.
Always check if the returned value is null before using the score.
redis
127.0.0.1:6379> ZSCORE myset "nonexistent" (nil) # Correct usage: 127.0.0.1:6379> ZADD myset 50 "member1" (integer) 1 127.0.0.1:6379> ZSCORE myset "member1" "50"
Output
(nil)
(integer) 1
"50"
Quick Reference
| Command | Description | Return Value |
|---|---|---|
| ZSCORE key member | Get the score of member in sorted set | Score as string or null if not found |
| ZADD key score member | Add member with score to sorted set | Number of elements added |
| ZRANGE key start stop WITHSCORES | Get members in range with scores | List of members and scores |
Key Takeaways
ZSCORE returns the score of a member in a sorted set or null if the member is missing.
The key must be a sorted set; otherwise, ZSCORE will return an error.
Always check for null to handle missing members safely.
Use ZADD to add members before querying their scores with ZSCORE.
ZSCORE returns the score as a string, not a number.