Start learning free

LESSON 63 OF 66 · NOSQL: REDIS

Sorted Sets: A Leaderboard

Practice

A leaderboard lists things by a number, highest first, like a shop's best sellers by units sold. A Redis sorted set keeps one for you. It stores each name once with a number called its score, and it always keeps the names in order of score, whatever order you add them in.

r.zadd(key, {name: score, ...}) adds names with their scores. r.zrevrange(key, start, end) gives back a list of names from the highest score down. Positions start at 0 and the end is included, so 0, 2 is a top 3, like ORDER BY score DESC LIMIT 3 in SQL. Add withscores=True to get (name, score) pairs; scores come back as floats, like 7.0.

r.zincrby(key, amount, name) adds to one score, and Redis moves the name to its new place. r.zrevrank(key, name) gives back a name's position from the top, starting at 0; r.zrank counts from the bottom.

r.zadd("views", {"Lamp": 40, "Desk": 25, "Rug": 12})
print(r.zrevrange("views", 0, 1))   # ['Lamp', 'Desk']
r.zincrby("views", 20, "Rug")       # Rug now has 32
print(r.zrevrank("views", "Rug"))   # 1: second from the top

This lesson runs on an in-memory stand-in for Redis that starts empty; the same code runs unchanged on a real Redis server. The starting code gives you sold, a dict of units sold per product. Your script must print:

Top 3: ['Pen', 'Mug', 'Notebook']
Now: [('Pen', 15.0), ('Mug', 7.0), ('Teapot', 6.0)]
Teapot's place: 3

Your task: put every product in sold into the sorted set "best_sellers" and print the top 3. Then add 4 sales to the Teapot, print the top 3 again with scores, and print the Teapot's place counted from 1.


Assignment
Follow the Coding Tutorial to build a best-sellers leaderboard with zadd, read it with zrevrange, update it with zincrby and find a place with zrevrank.


Hint
zrevrange and zrevrank count from the highest score, starting at 0. The best seller is at position 0, so add 1 to get the place people read.


STEP 1 OF 5
    Ctrl + Enter to check