Leaderboards
Maintain a ranking that changes as players or entities receive scores.
Redis · Command
Adds members with scores to a sorted set, updating existing members and creating the key when needed. Options can restrict updates, count changed entries, or increment one member's score.
ZADD adds score-member pairs to the sorted set at key. A missing key is created; an existing member is repositioned when its score changes. Options can restrict updates, count changed entries, or return the new score while incrementing one member.
ZADD key [NX | XX] [GT | LT] [CH] [INCR] score member [score member ...]| Name | Type | Description |
|---|---|---|
key | key | Name of the key that holds the sorted set. |
score member [score member ...] | pairs | One or more score-member pairs; each score is a double-precision floating-point number. |
NX | option | Add only new members. |
XX | option | Update only existing members. |
CH | option | Count changed members, including score updates. |
INCR | option | Increment one member's score instead of setting it. |
GT | option | Update only when the new score is greater. |
LT | option | Update only when the new score is less. |
Integer reply: newly added members by default, or newly added and updated members with CH. With INCR, returns the updated score as a double. A null reply is returned when a conditional NX, XX, GT, or LT operation is aborted.
redis-cli ZADD leaderboard 100 alice 125 bob
redis-cli ZADD leaderboard GT 130 alice
redis-cli ZRANGE leaderboard 0 -1 REV WITHSCORESAdds two members, raises Alice's score only when the new score is greater, then lists the leaderboard from highest to lowest score.
Maintain a ranking that changes as players or entities receive scores.
Store items ordered by numeric priority for range and rank queries.
Atomically update a single member's score while retrieving its new value.
ZADD inserts members into a sorted set and associates each with a double-precision score. If a member already exists, its score is updated and the member is placed according to the resulting order; a nonexistent key is created.
Follow-up: How does ZADD behave when the key has another type? It returns an error because the key must hold a sorted set.
Without CH, the integer reply counts only newly added members. With CH, it counts both newly added and updated members.
Follow-up: What does INCR return? It returns the member's updated score as a double, or a null reply when the conditional operation is not performed.
NX permits only new members, while XX permits updates only for existing members. GT and LT constrain updates to cases where the new score is respectively greater or less than the current score.
Follow-up: Can GT and LT be used together? No; the mutually exclusive option pairs must not be combined, and INCR permits only one score-member pair.
ZINCRBYZRANGEZREVRANGEZRANKZREVRANKZREMZMSCORE