A Redis sorted set is a data structure that combines set and sorted list features. It allows you to save a collection of unique items while assigning each element a score or rank. Because this score is used to determine the order of the set's members, sorted sets are an ideal option for applications that require ordered data.
1. Size Limitation
A Redis sorted set can have a maximum of 4,294,967,295 items as members.
2. Create Sorted Set
The ZADD command in Redis may be used for creating a sorted set. The ZADD command accepts three parameters:
The sorted set key's name.
The member whose score you are adding.
The importance of the new member.
127.0.0.1:6379> ZADD testsortedset 1 "keyboard" 2 "mouse" 3 "cpu" 4 "gpu"
(integer) 4
127.0.0.1:6379> ZRANGE testsortedset 0 4
1) "keyboard"
2) "mouse"
3) "cpu"
4) "gpu"
127.0.0.1:6379>
3. Get the score associated with the given member in a sorted set
The Redis ZSCORE command returns the score of the provided sorted set member. If the member or the key does not exist in the sorted set, nil is returned.
127.0.0.1:6379> ZSCORE testsortedset mouse
"2"
127.0.0.1:6379> ZSCORE testsortedset cpu
"3"
127.0.0.1:6379>
4. Remove one or more members from a sorted set
The ZREM command in Redis removes one or more members from a sorted set. The command is ignored if the members do not exist in the sorted set.
127.0.0.1:6379> ZREM testsortedset gpu
(integer) 1
127.0.0.1:6379> ZRANGE testsortedset 0 4
1) "keyboard"
2) "mouse"
3) "cpu"
127.0.0.1:6379>
5. Determine the index of a member in a sorted set The ZRANK command in Redis returns the rank of a specified member of a sorted collection. The rank indicates the member's position in the sorted set, with the lowest score having a rank of 0. If the member or the key does not exist in the sorted set, nil is returned.
127.0.0.1:6379> ZRANK testsortedset cpu
(integer) 2
127.0.0.1:6379>
Comments