Querying Redis Sorted Set Elements
The Redis sorted sets are quite different from the normal sets. Even though both set types store the unique members inside, the sorted sets put the elements in an ordered manner. The main properties of the Redis sorted set are:
- Each element assigned to a unique index(rand) starting from 0
- Score order-based index per each element
- Lexicographical order-based index per each element
Hence, the Redis sorted set members can be retrieved based on multiple measures such as score, rank (index), and lexicographical. ZRANGEBYSCORE and ZRANGE are the two main Redis sorted set commands that can be used to iterate over the members based on the previously stated measures. In this guide, we will focus on the ZRANGEBYSCORE command that is used to query members by a range of score values.
The ZRANGEBYSCORE Command
Since the ZRANGEBYSCORE command has a logarithmic time complexity, it is very fast at retrieving the sorted set elements. In addition, the command options like LIMIT reduce the retrieval time by a considerable amount. Hence, the ZRANGEBYSCORE command is safe to use in the low latency real-time applications like online leaderboards, priority queues, and secondary indexing in general.
Syntax:
sorted_set_key: This is the unique identifier where the sorted set is stored at.
minimum_score: The lower boundary score value of the specified range.
maximum_score: The higher boundary score value of the specified range.
WITHSCORES: This optional argument returns each element’s score.
LIMIT: This optional argument can be used to limit the returning element count from a specified position of the sorted set.
The ZRANGEBYSCORE command returns the sorted set members between the specified minimum_score and maximum_score scores. Those members are returned in ascending order based on the score values. If the multiple members have the same scores, the command follows the lexicographical ordering.
Example: Online Game Leaderboard Based on Player Experience
Let’s assume that it is an online game where each player can gain experience points when they complete the missions, discover quests, and defeat the enemies. Since Redis sorted sets are responsive and the in-memory data structures where members are ordered based on a score, they can be used to store the player details. In turn, the information can be returned with low latency.
As shown in the previous illustration, the player information can be added to a Redis sorted set and can manipulated later on when needed.
Let’s add the four players shown in the previous illustration. We will usethe ZADD command to create and add the player details to the sorted set “leaderboard:XP”.
zadd leaderboard:XP 2500 Player:02
zadd leaderboard:XP 1000 Player:03
zadd leaderboard:XP 3500 Player:04
Query All the Players in the Game Leaderboard
We can use the ZRANGEBYSCORE command to fetch all the players in the game leaderboard as shown in the following. The minimum and maximum score values are specified as 1000 and 3500. We can use the -inf and +inf values if we are not sure about the lowest and highest score values:
OR
zrangebyscore leaderboard:XP -inf +inf
All the members are returned as in the following output:
The output is sorted in the ascending order by score values.
Exclude the Minimum_Score or Maximum_Score Values
In the previous example, the min and max score values are inclusive of the range. We can exclude the min and max score values from the range by prefixing the score with the “(“ character as shown in the following:
As shown in the following output, the output excludes the members whose scores are 1000 and 3500.
Display Both the Member and Score Values Together
We can use the WITHSCORES optional argument with the ZRANGEBYSCORE command to display the score values per member.
Output:
Limit the Number of Members Returned
In some scenarios, we need to limit the number of returned members per call. Let’s say we need to get the top 2 members whose experience values (score) are the lowest. We can use the LIMIT argument with the count of 2 and offset of 0. The offset is the rank per member.
This returns the top 2 members whose scores are the lowest.
You can use the LIMIT argument with the WITHSCORES argument as well.
ZRANGE Command Instead of ZRANGBYSCORE
With the Redis 6.2.0 version, the ZRANGEBYSCORE command is deprecated. Hence, we can use the ZRANGE command that behaves the same as the ZRAGNEBYSCORE command when it is used with the BYSCORE optional argument.
Conclusion
In summary, the ZRANGEBYSCORE command is used to query the members between the specified minimum and maximum score values of a Redis sorted set stored at a given key. As stated, this command has a logarithmic time complexity that can be used to iterate over a set of members with low latency. Also, it supports a couple of optional arguments, LIMIT and WITHSCORES, which limit the returned member count and displays both the member-score value pairs.