Let’s break the word “sorted set” into two words, sorted, which means order, and set, which means the items are unique. Hence, a sorted set is a data structure in Redis that stores unique values in a sorted way.
Every member in the sorted set is associated with a score that determines its order among other elements in the set.
Some of the essential commands associated with sorted sets are as follows:
ZADD
commandThe ZADD
command creates and adds one or member to the sorted set.
The syntax is as follows:
ZADD key score member
Where:
key
: This parameter is the name under which the sorted set is registered.score
: This parameter is the score value associated with the member.member
: This parameter is the member to add.ZSCORE
commandThe ZSCORE
command retrieves the score associated with the given member.
The syntax is as follows:
ZSCORE key member
Where:
key
: This parameter is the name under which the sorted set is registered.member
: This parameter is the member for which the score has to be retrieved.ZRANK
commandThe ZRANK
command is used to retrieve the index of the member in the sorted set ordered from low to index. The rank or the index is zero-based, i.e., the rank of the member with the lowest score is 0.
The syntax is as follows:
ZRANK key member
Where:
key
: This parameter is the name under which the sorted set is registered.member
: This parameter is the member for which the rank has to be retrieved.ZREM
commandThe ZREM
command removes the given member from the sorted set.
The syntax is as follows:
ZREM key member
Where:
key
: This parameter is the name under which the sorted set is registered.member
: This parameter is the member to be removed.ZRANGE
commandThe ZRANGE
command is used to retrieve all the members of the sorted set that fall in the range of the given values.
The syntax is as follows:
ZRANGE key min max
Where:
key
: This parameter is the name under which the sorted set is registered.min
: This parameter is the minimum value.max
: This parameter is the maximum value.ZINCRBY
commandThe ZINCRBY
command is used to increment the member’s score by the specified amount.
The syntax is as follows:
ZINCRBY key increment member
Where:
key
: This parameter is the name under which the sorted set is registered.increment
: This parameter is the amount to increment.member
: This parameter is the sorted set member.ZCOUNT
commandThe ZCOUNT
command retrieves the count of members with a score between min and max.
The syntax is as follows:
ZCOUNT key min max
Where:
key
: This parameter is the name under which the sorted set is registered.min
: This parameter is the minimum value.max
: This parameter is the maximum value.ZCARD
commandThe ZCARD
command retrieves the number of members in the sorted set.
The syntax is as follows:
ZCARD key
Where:
key
: This parameter is the name under which the sorted set is registered.Run the above commands in the following terminal.
Free Resources