How to Use ZADD in Redis: Syntax and Examples
Use the
ZADD command in Redis to add one or more members with scores to a sorted set. The syntax is ZADD key score member [score member ...], where each member is associated with a numeric score that determines its order in the set.Syntax
The ZADD command adds members to a sorted set stored at a given key. Each member has a numeric score that Redis uses to sort the set in ascending order.
- key: The name of the sorted set.
- score: A number representing the member's score.
- member: The value to add to the sorted set.
- You can add multiple
score memberpairs in one command.
redis
ZADD key score member [score member ...]
Example
This example adds three members with scores to a sorted set called players. It then retrieves all members with their scores in ascending order.
redis
127.0.0.1:6379> ZADD players 100 "Alice" 200 "Bob" 150 "Charlie" (integer) 3 127.0.0.1:6379> ZRANGE players 0 -1 WITHSCORES 1) "Alice" 2) "100" 3) "Charlie" 4) "150" 5) "Bob" 6) "200"
Output
1) "Alice"
2) "100"
3) "Charlie"
4) "150"
5) "Bob"
6) "200"
Common Pitfalls
Common mistakes when using ZADD include:
- Forgetting that scores must be numeric values.
- Mixing up the order of
scoreandmemberarguments. - Using the wrong key type (the key must be a sorted set or not exist).
- Expecting
ZADDto update scores without specifying the member again.
Here is an example showing a wrong and correct usage:
redis
127.0.0.1:6379> ZADD myset "Alice" 100 (error) ERR value is not a valid float # Correct usage: 127.0.0.1:6379> ZADD myset 100 "Alice" (integer) 1
Output
(error) ERR value is not a valid float
(integer) 1
Quick Reference
| Option | Description |
|---|---|
| key | Name of the sorted set |
| score | Numeric score for sorting |
| member | Value to add to the set |
| NX | Only add new members (ignore existing) |
| XX | Only update existing members |
| CH | Return number of elements changed |
| INCR | Increment the score of a member |
Key Takeaways
ZADD adds members with scores to a Redis sorted set for ordered storage.
Scores must be numeric and come before the member in the command.
You can add multiple members in one ZADD command by repeating score-member pairs.
Use options like NX, XX, CH, and INCR to control how members are added or updated.
Always ensure the key is a sorted set or does not exist before using ZADD.