Lesson 2

Welcome back! Building on our previous experience with Redis sets, today we are diving into **sorted sets**. **Redis sorted sets** combine the power of sets and lists, allowing us to handle collections in which every member is unique but has an associated score. These scores ensure the elements are kept in a specific, sorted order.

In this lesson, you will understand how to use **sorted sets** in Redis. Specifically, we will focus on:

- Adding members and scores to a sorted set.
- Retrieving top members based on their scores.
- Checking the total number of players.
- Getting the rank of a specific player.
- Removing members from a sorted set.

**Sorted sets** in Redis are remarkable due to their efficiency and flexibility. You might find them particularly useful for scenarios like maintaining **leaderboards**, scheduling tasks, or storing time-series data.

Let's start by exploring how to work with **sorted sets** in Redis.

JavaScript`1import { createClient } from 'redis'; 2 3// Connect to Redis 4const client = createClient({ 5 url: 'redis://localhost:6379' 6}); 7 8client.on('error', (err) => { 9 console.log('Redis Client Error', err); 10}); 11 12await client.connect(); 13 14for (const item of [{ score: 100, value: 'Alice' }, { score: 400, value: 'Bob' }, { score: 300, value: 'Charlie' }]) { 15 await client.zAdd('leaderboard', item); // Add members to the sorted set 16} 17 18const leaderboard = await client.zRangeWithScores('leaderboard', 0, -1); // Retrieve all members with scores in ascending order 19console.log(leaderboard); // [{ score: 100, value: 'Alice' }, { score: 300, value: 'Charlie' }, { score: 400, value: 'Bob' }] 20 21const totalNumberOfPlayers = await client.zCard('leaderboard'); // Get the total number of players 22console.log('Total number of players:', totalNumberOfPlayers); // 3 23 24const topTwoPlayers = await client.zRange('leaderboard', -2, -1); // Retrieve top two players with scores in ascending order 25console.log(topTwoPlayers); // ['Charlie', 'Bob'] 26 27let playerRank = await client.zRevRank('leaderboard', 'Charlie'); // Get the rank of a specific player in descending order 28console.log('Charlie rank:', playerRank); // 1, since Charlie is the second-highest scorer after Bob 29 30await client.zRem('leaderboard', 'Bob'); // Remove a player from the sorted set 31playerRank = await client.zRevRank('leaderboard', 'Charlie'); // Get the rank of a specific player after removal 32console.log('Charlie rank:', playerRank); // 0, since Charlie is now the highest scorer after Bob's removal 33 34await client.disconnect();`

Let's break down the commands used in the code snippet:

`zAdd`

: Adds members to a sorted set with their corresponding scores. In the example, we add three players with their scores to the`leaderboard`

sorted set.`zRangeWithScores`

: Retrieves all members with scores from the sorted set in ascending order. The output is an array of objects containing the score and value of each member. Note, that sorted set stores members in ascending order of their scores, so to get the top members, you need to use the`zRangeWithScores`

command with negative indices to specify the range from the end. The result is an array of objects containing the score and value of each member in ascending order.`zCard`

: Returns the total number of members in the sorted set. In the example, we get the total number of players in the`leaderboard`

sorted set.`zRange`

: Retrieves a range of members from the sorted set. In the example, we get the top two players from the`leaderboard`

sorted set.`zRevRank`

: Returns the rank of a specific member in descending order. In the example, we get the rank of the player`Charlie`

in the`leaderboard`

sorted set.`zRem`

: Removes a specific member from the sorted set. In the example, we remove the player`Bob`

from the`leaderboard`

sorted set.

Redis **sorted sets** are essential for several reasons:

**Order and Uniqueness:**By maintaining both order and uniqueness, sorted sets are highly suited for ranking systems, similar to what you see in games or competition leaderboards.**Efficient Operations:**With commands like`zAdd`

,`zRangeWithScores`

, and`zRem`

, you can quickly add, retrieve, and manage sorted data, enhancing the performance and functionality of your applications.**Practical Applications:**From tracking high scores in a game to sorting real-time stock prices, sorted sets provide a robust solution for handling sorted data efficiently.

Exciting, isn't it? Now, let's proceed to the practice section to apply what we've learned. Together, we will solidify your understanding by working through some real-world examples and exercises.