What Is a Redis Sorted Set?

A Redis sorted set is one of the five basic data structures in Redis, alongside strings, lists, sets, and hashes. But what is a Redis sorted set exactly, and how do Redis sorted sets work? Below, we'll discuss everything you need to know about Redis sorted sets, including the commands that operate on them, such as ZADD, ZRANGE, ZRANGEBYSCORE, and ZREMRANGEBYSCORE.

What Are Redis Sorted Sets?

A Redis sorted set (sometimes called a "ZSet") stores a collection of unique members, where each member is paired with a floating-point number known as its score. Like a regular Redis set, a sorted set cannot contain duplicate members. Unlike a regular set, however, the members are always kept in order according to their score.

This ordering is what makes sorted sets so useful. Because Redis maintains the order every time a member is added or updated, you can retrieve the highest- or lowest-ranked members, or every member within a range of scores, without scanning or sorting the data yourself.

For example, a sorted set is the natural way to build a real-time leaderboard: each player is a member, and their points are the score. The same structure works well for priority queues (where the score is a priority or timestamp), rate limiters (where the score is the time of each request), and any use case that needs items ranked by a numeric value.

How Do Redis Sorted Sets Work?

In a Redis sorted set, members are unique strings and scores are double-precision floating-point numbers. When two members share the same score, Redis breaks the tie by ordering them lexicographically. Adding, removing, and updating members are all fast operations, and Redis can return a member's exact rank or a range of members almost instantly, because the set is always sorted.

Some of the most common Redis sorted set commands are as follows:

  • ZADD: Adds one or more members with their scores to the sorted set, or updates the score of members that already exist.
  • ZRANGE: Returns a range of members by their index (rank) position, from lowest score to highest.
  • ZRANGEBYSCORE: Returns all members whose score falls within a given minimum and maximum range.
  • ZREMRANGEBYSCORE: Removes all members whose score falls within a given minimum and maximum range.
  • ZSCORE: Returns the score associated with a given member.
  • ZRANK: Returns the rank (index) of a member, ordered from the lowest score to the highest.
  • ZINCRBY: Increments the score of a member by a given amount.
  • ZREM: Removes one or more members from the sorted set.

Below is a simple demonstration of creating and using a Redis sorted set. This first command adds three members, each with a score, using ZADD:

zadd leaderboard 4200 alice 3900 bob 5100 carol

If the members did not already exist, Redis returns the number of new members added — in this case, "(integer) 3".

Running ZRANGE with the withscores option returns the members in ascending score order, along with their scores:

zrange leaderboard 0 -1 withscores

1) "bob"
2) "3900"
3) "alice"
4) "4200"
5) "carol"
6) "5100"

ZRANGEBYSCORE returns only the members whose score falls inside a range — for example, everyone scoring between 4000 and 5200:

zrangebyscore leaderboard 4000 5200

1) "alice"
2) "carol"

Finally, ZREMRANGEBYSCORE trims the set by removing every member within a score range. This command deletes all members scoring below 4000:

zremrangebyscore leaderboard 0 3999

Redis returns the number of members removed, in this case "(integer) 1" for "bob".

Redis Sorted Sets in Java with Redisson

Redis makes it easy to build ranked, high-performance data structures. Despite the benefits of Redis, however, it's not immediately compatible with the Java programming language out of the box.

The good news: Java developers can lower their Redis learning curve by installing a third-party Redis Java client such as Redisson. Redisson includes many familiar Java objects and constructs, so that developers can spend less time learning the platform and more time actually building.

Among the many features of Redisson is the RScoredSortedSet interface, a distributed Java object backed by Redis sorted sets. It maps the raw sorted set commands to type-safe Java methods, so ZADD, ZRANGE, ZRANGEBYSCORE, and ZREMRANGEBYSCORE all become simple method calls.

Below is an example of how to use RScoredSortedSet in Redisson to work with a Redis sorted set:

RScoredSortedSet<String> board = redisson.getScoredSortedSet("leaderboard");

// ZADD — add a member with a score, or atomically update an existing one
board.add(4200, "alice");
Double total = board.addScore("bob", 150);

// ZRANGE — read members by rank (index 0 is the lowest score)
Collection<String> lowestThree = board.valueRange(0, 2);

// ZRANGEBYSCORE — read members within a score band
Collection<String> midTier = board.valueRange(4000, true, 5200, true);

// ZREMRANGEBYSCORE — remove members within a score range
int removed = board.removeRangeByScore(0, true, 3999, true);

Redisson includes several important features to improve the functionality and performance of sorted sets:

  • Atomic score updates: Methods such as addScore increment a member's score atomically, so concurrent updates from multiple servers are never lost to race conditions.
  • Rank in a single round trip: Methods such as addScoreAndGetRevRank combine a write and a rank lookup into one network call, ideal for instantly telling a user their new position.
  • Data partitioning: Data can be partitioned across multiple Redisson clusters, helping you scale database operations.

The Redisson PRO edition performs read/write operations up to 4x faster.

Similar Terms