Course Content
Introduction to Redis
Introduction to Redis
Sorted Set
Elements are automatically sorted by their score, allowing for efficient sorting and retrieval operations.
The image illustrates a Redis sorted set, where elements are ordered by their numeric score. Each element is unique and paired with a score that determines its position in the set.
Key Commands
To add an element to a sorted set, use the ZADD
command. If the element already exists, its score is updated. To remove an element, use the ZREM
command.
To retrieve elements with their scores, use the ZRANGE
command with the WITHSCORES
option:
This command returns all elements in the leaderboard set along with their scores. If you only want the elements without their scores, omit the WITHSCORES
parameter.
To retrieve elements within a specific score range, use the ZRANGEBYSCORE
command:
This will select all elements with scores between 500
and 1500
.
Commands like ZCOUNT
and ZRANK
are useful for counting elements within a score range and finding the rank of a specific element in a sorted set:
1. What range should you use with the ZRANGE
command to retrieve all elements in a Redis sorted set?
2. What happens if you add an element with an existing value to a sorted set?
Thanks for your feedback!