Learnitweb

Redis Sorted Sets (SSet) Tutorial

In this lecture, we will learn about Redis Sorted Sets (SSet), a powerful data structure that combines the characteristics of a set and a sorted list. Sorted sets allow you to store unique items along with a score, and automatically maintain them in ascending order of scores.


1. Overview of Sorted Sets

  • A Sorted Set is a collection of unique elements.
  • Each element is associated with a score (typically numeric).
  • Elements are automatically sorted by their score.
  • Operations supported include:
    • Adding elements
    • Incrementing scores
    • Fetching elements by rank or score range
    • Removing elements

Sorted Sets are useful for leaderboards, rankings, and priority-based storage.


2. Creating and Adding Elements

Step 1: Create a Sorted Set

RScoredSortedSetReactive<String> students = redissonClient.getScoredSortedSet("students");
  • Here, "students" is the key for the sorted set.
  • We are using reactive Redis for asynchronous operations.

Step 2: Adding Elements

There are two main methods to add elements:

  1. addScore:
    • If the element is not present, it sets the given score.
    • If the element already exists, it adds the new score to the existing score.
students.addScore("Jake", 2.2);
students.addScore("Sam", 3.2);
students.addScore("Mike", 2.5);
  1. add:
    • Adds the element with the score.
    • Replaces the existing score if the element already exists.
students.add(4.0, "Andrew");  // Score comes first, then element

Important: In Redis Sorted Sets, the score comes before the element.


3. Retrieving Elements

Step 1: Fetch by Rank

  • Redis sorted sets maintain a rank based on score (ascending order by default).
  • The rank index starts at 0.
  • You can fetch elements using a rank range:
students.valueRange(0, 1).subscribe(System.out::println);
  • Output (ascending by score):
Jake
Sam

Step 2: Fetch by Reverse Rank

  • Fetch elements in descending order of score:
students.valueRangeReversed(0, 1).subscribe(System.out::println);
  • Useful for leaderboards, where the highest score comes first.

Step 3: Flattening Collections

  • If your operations return collections, you can flatten them to get individual elements:
.flatMapIterable(Function.identity())
  • This converts nested collections into a stream of elements for processing.

4. Updating Scores

  • If you add an element that already exists using addScore, the existing score increases.
  • Using add, the existing score is replaced.
  • Example:
students.addScore("Jake", 2.0);  // Jake's score is incremented
students.add(5.0, "Sam");        // Sam's score is replaced with 5.0
  • This behavior is useful for leaderboards where scores can increase over time.

5. Example: Complete Workflow

RScoredSortedSetReactive<String> students = redissonClient.getScoredSortedSet("students");

// Adding elements
students.addScore("Jake", 2.2);
students.addScore("Sam", 3.2);
students.addScore("Mike", 2.5);

// Adding a new element
students.add(4.0, "Andrew");

// Fetch first two elements by ascending score
students.valueRange(0, 1)
        .subscribe(System.out::println);

// Fetch top two elements by descending score
students.valueRangeReversed(0, 1)
        .subscribe(System.out::println);

// Increment Jake's score
students.addScore("Jake", 2.0);
  • Output after operations:
    • Ascending: Jake, Mike
    • Descending: Sam, Andrew

Note: The ranking will update automatically after each operation.


6. Key Points

  • addScore: increments the score if the element exists; sets it if it doesn’t.
  • add: replaces the existing score.
  • Sorted Sets maintain unique elements and automatic ordering.
  • Fetch by rank or score range for flexibility.
  • Flatten collections when needed to process individual items.
  • Ideal for leaderboards, scoring systems, and priority-based queues.