Skip to the workspace
Pebellslearn by building
Sorted Sets  ›  Lesson

ZADD and ZRANGE

ZADD 12 minZADD puts members into a sorted set with a score, and ZRANGE reads them back by position, lowest score first unless you add REV.

redis / ZADD and ZRANGE

Explore each scene at your own pace.

01 · The rule

The rule

ZADD and ZRANGE

Wordcraft's leaderboard changes every few seconds as games finish, and every player's screen shows the top of it. Sorting all players by score on every page view would be slow. A sorted set keeps them in order all the time, so reading the top is instant.

The rule

ZADD gives each member a score; ZRANGE reads them lowest first.

A sorted set holds unique members, each with a number called its score. Redis keeps the members ordered by score at all times. (Its type name is zset, which is why every command starts with Z.)

127.0.0.1:6379> ZADD leaderboard 320 asha 150 ravi 410 meera 90 tom
(integer) 4
127.0.0.1:6379> ZRANGE leaderboard 0 -1
1) "tom"
2) "ravi"
3) "asha"
4) "meera"
127.0.0.1:6379> ZRANGE leaderboard 0 1 REV WITHSCORES
1) "meera"
2) "410"
3) "asha"
4) "320"
  • ZADD key score member [score member ...]: note the score comes first. The reply counts members that were added; changing an existing member's score does not count.
  • ZRANGE key start stop returns members by position, lowest score first. Positions start at 0, both ends are included, and -1 means the last one, so 0 -1 is everything.
  • REV flips the order to highest first, which is what a leaderboard wants.
  • WITHSCORES puts each member's score after it, alternating member and score.

Two members with the same score are ordered alphabetically by member name.

ZADD also takes options: NX only adds new members, XX only updates existing ones, and GT or LT only update when the new score is greater or lower, perfect for "keep each player's best score".

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.