Exploring Sorted Sets in Redis Using Go

Exploring Sorted Sets in Redis Using Go

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 where every member is unique but has an associated score. These scores ensure the elements are kept in a specific, sorted order.

What You'll Learn

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

  1. Adding members and scores to a sorted set.
  2. Retrieving top members based on their scores.

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 connecting to your Redis server and adding some members to a sorted set:

package main

import (
    "fmt"
    "github.com/redis/go-redis/v9"
    "context"
)

func main() {
    ctx := context.Background()

    // Connect to Redis
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379", // Add your Redis server address
        DB:   0,                // Use the default database
    })

    // Adding scores and members to a sorted set
    client.ZAdd(ctx, "leaderboard", redis.Z{Score: 100, Member: "Alice"})
    client.ZAdd(ctx, "leaderboard", redis.Z{Score: 400, Member: "Bob"})
    client.ZAdd(ctx, "leaderboard", redis.Z{Score: 300, Member: "Charlie"})
    client.ZAdd(ctx, "leaderboard", redis.Z{Score: 350, Member: "Alice"})

    // Retrieving top players
    topPlayers, _ := client.ZRevRangeWithScores(ctx, "leaderboard", 0, 1).Result()
    fmt.Println("Top 2 players:")
    for _, z := range topPlayers {
        fmt.Printf("Name: %s, Score: %f\n", z.Member, z.Score)
    }

    // Retrieve players with the lowest scores
    lowPlayers, _ := client.ZRangeWithScores(ctx, "leaderboard", 0, 1).Result()
    fmt.Println("Lowest 2 players:")
    for _, z := range lowPlayers {
        fmt.Printf("Name: %s, Score: %f\n", z.Member, z.Score)
    }

    // Removing members from a sorted set
    client.ZRem(ctx, "leaderboard", "Alice")
}

This code uses the ZAdd command to add members with their scores and the ZRevRangeWithScores command to get members in descending order of their scores.

Notice how we used the WithScores option to include scores in the result. This way, we can easily retrieve the top players along with their scores.

For this example, the output will be Top 2 players: Name: Bob, Score: 400.000000 Name: Alice, Score: 350.000000. Notice that the score for Alice is 350.0, not 100.0, as the last score is the one that is kept.

Similarly, the ZRangeWithScores command helps retrieve members in ascending order of their scores, which is useful when you want the lowest scores.

Notice, that sorted set functions all have a Z prefix, which stands for sorted sets in Redis. This makes it easier to identify and work with sorted set commands.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal