Managing data can be a pain if they end up getting cluttered, leaving you confused, thinking which is which. The good news is that Redis takes care of sorting your data automatically, resulting in not requiring additional processes to sort data manually. This behavior makes a Redis sorted set an ideal choice for real-time applications that require sorted data.
In this tutorial, you’ll learn how to effectively manage Redis sorted sets via the command-line interface (CLI).
Read on to never again worry about manually sorting your data sets!
Prerequisites
This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following.
- An Ubuntu server. This tutorial uses Ubuntu 20.04.
- Redis installed on your server.
- A user account with root/sudo privileges.
Configuring Redis
A few configuration directives are important for your Redis server, supervised
, and dbfilename
directives. By default, Redis stores its configuration parameters in the /etc/redis/redis.conf file.
The supervised directive tells Redis what kind of init system to use, and the available options are systemd, upstart, and none. But in this tutorial, you’ll use systemd to manage Redis.
1. SSH into your server and open the /etc/redis/redis.conf file with your favorite text editor.
sudo nano /etc/redis/redis.conf
2. Find the supervised directive and uncomment it by removing the leading pound sign (#), then set the value to systemd, as shown below. Once you’ve made the changes, save and exit the redis.conf file.
By default, this directive is commented out and set to 0 (none), which indicates you can not use systemd to manage your Redis server.
3. Open your terminal and run each of the following systemctl
commands to restart the Redis server to apply the changes.
The first two commands don’t have an output, but you’ll see the Redis server’s status after running the last one.
# Restart Redis Server
sudo systemctl restart redis
# Start Redis Server
sudo systemctl start redis
# Check Redis Server Status
sudo systemctl status redis
If all goes well, you’ll see an output similar to the following, showing the Redis server is active (running).
4. Finally, run the below commands to log in to your Redis server and ensure Redis is functioning correctly.
# Login to Redis Server
redis-cli
# Ping Redis Server to ensure Redis is working correctly.
ping
If you receive a PONG response, your Redis server is running, and you can continue to the next section.
Creating a Redis Sorted Set
Now that your Redis server is running, you can create a sorted set to store your data. Suppose you have a leaderboard of the users with the most active sessions on your server. You can create a sorted set to store the leaderboard data with a score representing the number of active sessions.
In the syntax below, the score
arguments are scores of the members in your sorted set, while the member
arguments are the IDs of the members in your sorted set as strings (""
).
ZADD key score1 "member1" score2 "member2" ... scoreN "memberN"
Now, run the ZADD
command below to create a sorted set called leaderboard
with one (1
) score for the user ata1
(member ID), indicating the user has one active session.
ZADD leaderboard 1 "ata1"
Since the member IDs are strings, Redis can adequately parse the arguments’ returned values and store them as a sorted set.
Like all Redis commands, the ZADD
command returns an integer response indicating the number of members added to the sorted set. In this case, you added one member to the leaderboard sorted set, as shown below.
Adding Multiple Members to a Sorted Set
You’ve just added one member, but can you add multiple members to the sorted set in one go? Yes! This behavior can be useful if you don’t want to issue the same command multiple times to add more members in a sorted set.
Run the below command to add members to the leaderboard
sorted set with different scores and IDs.
Note that in the command below:
- The scores are not required to be sequential or in order (
2 "ata2"
3 "ata3"
3 "ata4"
6 "ata5"
). - You can have gaps between the scores (
3 "ata4"
6 "ata5"
) - You can also have identical scores (
3 "ata3"
3 "ata4"
).
This behavior makes sorted sets unique from other data structures in Redis. You can take advantage of this property to store data in a way that is convenient for you.
ZADD leaderboard 2 "ata2" 3 "ata3" 3 "ata4" 6 "ata5" 2 "ata6" 7 "ata7" 10 "ata8" 11 "ata9"
Modifying ZADD
Command’s Behavior with Options
The ZADD
command supports the following options. Put these options after the key name and before the first score to modify the command’s behavior.
For example, you’ve found out that the ata1 user has increased activity and now has two active sessions. You can update ata1’s score by appending the XX
options in the ZADD
command. The XX
option only updates the existing elements in the sorted set with the new scores.
1. Run the following command to update ata1
‘s score to 2
without changing any of the other members’ in the leaderboard
sorted set.
ZADD leaderboard XX 2 "ata1"
The output below confirms Redis updated the ata1 member with a new score of 2. And the integer value is 0 since there are no new members added.
2. Next, run the below command to add ata10
to the leaderboard
sorted set. With the NX
option appended, the ZADD
command adds ata10
without affecting the scores of other members.
This command only adds ata10 if it does not exist in the leaderboard sorted set.
ZADD leaderboard NX 2 "ata1" 12 "ata10”
As you can see below, (integer) 1 indicates the ata10 user was added to the leaderboard sorted set with a score of 12.
You can’t use NX with the XX option. You must choose one or the other; otherwise, you’ll get the error below.
3. Lastly, run the ZADD
command below appending the CH
option.
The CH option returns the number of members whose scores changed or the number of new members added to the sorted set. This option can be useful for debugging your code or monitoring your sorted set’s health.
ZADD leaderboard CH 2 "ata2" 3 "ata3" 3 "ata4" 6 "ata5" 2 "ata6" 7 "ata7" 10 "ata8" 11 "ata9”
You’ll see that the CH option returns (integer) 0 because no members were added or had their scores changed, as shown below.
Fetching Members by Range of Scores from a Sorted Set
You’ve successfully created a sorted set with a few members, but is that all? Perhaps you have applications dependent on the members in your sorted set. If so, you’ll have to run a handful of commands to fetch members from a sorted set.
Run the zrange
command below to fetch the first six members (0
to 5
) from the leaderboard
sorted set. Zero (0
) is the first index, and five (5
) is the last index to return.
zrange leaderboard 0 5
As shown below, the command returns all the members in the sorted set with scores in the range of 0-5. Those members have a low score, so they may be less likely to be active users.
If your members have the same score, the
zrange
command returns them alphabetically.
Now, run the below zrange
command to fetch the last four members (-4 -1
) from the leaderboard
sorted set.
The zrange
command supports negative indexes to fetch members starting from the end of the sorted set. In the following command, -1
is the last index in the sorted set, while -4
is the fourth to the last index.
zrange leaderboard -4 -1
Negative indexes can be useful for pagination. For example, if you have a sorted set with 1,000 members and your application can only display the first 20 members at a time. In that case, negative indexes can fetch the last 20, 40, 60, and so on., members from the sorted set for pagination.
Fetching Members and their Corresponding Scores
You’ve seen how to fetch a range of members from a sorted set. But the zrange
command, without options, only returns the members ID. What about the scores? You’ll run the same zrange
command but appended by the WITHSCORES
option this time.
Run the below command to fetch the first six members (0
5
) from the leaderboard
sorted set with their corresponding scores (WITHSCORES
).
zrange leaderboard 0 5 WITHSCORES
By default, Redis returns the members in ascending order. But perhaps you prefer to fetch the members from a sorted set in reverse order. If so, replace zrange
with the zrevrange
command instead.
Run the below zrevrange
command to fetch members with the highest scores on the top.
zrevrange leaderboard 0 11 WITHSCORES
Fetching Members with the Same Scores Alphabetically
You’ll meet situations where you have to deal with many members (even thousands) with the same score. In these cases, the zrangebylex
command will come in handy.
The zrangebylex
command lets you force Redis to return the members in alphabetical order. Redis will use the alphabetical order of the string instead of the score to return the members.
The zrangebylex
command has the following syntax.
zrangebylex key [start interval [stop interval.
Run the following commands to create a new sorted set (zadd
) called leaderboard2
, and fetch all the members (zrangebylex
) from leaderboard2 in alphabetical order ([a [z
).
# Creates leaderboard2 sorted set with multiple members
zadd leaderboard2 0 ata 0 bta 0 cta 0 dta 0 eta
# Fetches all the members in the leaderboard2 sorted set in alphabetical order (a-z).
zrangebylex leaderboard2 [a [z
You can see below that the members are listed in alphabetical order (a-z).
Note that the
zrangebylex
command is case-sensitive. So, if you have members with names such as Mary, mary, and MARY, they are all considered different members.
Now, run the commands below to add new members (zadd
) to the leaderboard2
sorted set and fetch the members (zrangebylex
) that start with capital letters alphabetically ([A [Z
).
# Adds new members with capital letters
zadd leaderboard2 0 Ata 0 Bta 0 Cta 0 Dta 0 Eta
# Fetches all the members with IDs starting with capital letters in alphabetical order
zrangebylex leaderboard2 [A [Z
Below, all members start with a capital letter and are listed in alphabetical order.
Fetching Members Rank and Score
Apart from fetching members alphabetically, you can also fetch members’ rank and score by running the zrevrank
command.
The member’s rank is just an integer number but can be useful for determining the importance of a member in a set. For example, if you aim to know which member has the most section points, the members’ rank can help.
Run the following commands to fetch the rank of members ata1
and ata9
in the leaderboard
sorted set.
zrevrank leaderboard ata1
zrevrank leaderboard ata9
As shown below, the ata1 member has a score of 2 and is ranked 9 (almost at the bottom). In contrast, the ata9 member has a score of 11 and is ranked 1 (at the top).
Fetching Information About a Sorted Set
You already know how to add and fetch members from a sorted set. But your app might need to fetch further information, like the following:
- The total number of members in a sorted set. If a sorted set contains no members, your app might choose to add some.
- Members that fall within a specific range of scores.
- If a member exists in a sorted set, your app might choose to update its score. But if not, your app might choose to add it.
Redis offers some commands you can use to get more information about a sorted set. One of those commands is the zcard
command. The zcard
command lets you get the total number of members (cardinality) in a sorted set.
1. Run the below zcard
command to fetch the total number of members in the leaderboard
sorted set.
zcard leaderboard
Below, the zcard command returns ten members in the leaderboard sorted set below.
2. Next, run the following command to fetch the number of members in the leaderboard
sorted set with scores between 8
and 10
. For example, these scores may indicate who is highly engaged in your website.
zcount leaderboard 8 10
3. Lastly, run the zrank
command below to find the rank of the member ata20
in the leaderboard
sorted set. This command lets you find out if a member exists in a sorted set and, if it does, fetch what its rank is.
zrank leaderboard ata20
When a member does not exist in a sorted set, the zrank command returns nil, as shown below.
Removing Members from a Sorted Set
A sorted set is a great way to store data, but your data can only be as good as when it’s up-to-date. Perhaps you have one too many members in your sorted set. If so, how do you remove some of them?
Suppose you have a sorted set called “players” that contains the players currently playing in your game. And as players leave the game, you need to remove them from the “players” sorted set.
Redis offers a few different commands for removing members from a sorted set, and one of them is the zrem
command. The zrem
command removes one or more members from a sorted set, following the syntax below.
zrem key member1 member2 ... memberN
To remove members from your sorted set:
1. Run the below zrem
command to remove the member ata1
from the leaderboard
sorted set.
zrem leaderboard ata1
2. Next, run the below command to remove all members containing A and Z in their name from the leaderboard2
sorted set. The command removes all members with the same score in alphabetical order ([A [Z
).
zremrangebylex leaderboard2 [A [Z
3. Run the below zremrangebyrank
command to remove members in the 1 – 4 score range from the leaderboard
sorted set. The zremrangebyrank
command lets you remove members based on their rank.
zremrangebyrank leaderboard 1 4
4. Finally, run the zrange
command below to verify that you’ve successfully removed the specified members (steps one to three) from the leaderboard
sorted set.
zrange leaderboard 0 10 WITHSCORES
zrange leaderboard2 0 10 WITHSCORES
Conclusion
Throughout this tutorial, you’ve learned about managing sorted sets in Redis. From creating sorted sets to adding and removing members and fetching data from sorted sets.
Redis sorted sets are a great way to store sorted data. By using the various Redis commands, you can keep your data up-to-date.
At this point, you should know the basics of sorted sets. So why not start using sorted sets in your own applications.