当前位置:网站首页>Redis introduction complete tutorial: detailed explanation of ordered collection

Redis introduction complete tutorial: detailed explanation of ordered collection

2022-07-04 23:00:00 Gu Ge academic

Ordered sets are relative to hashes 、 list 、 It will be a little strange for the collection , But since it's called order
aggregate , So it must have something to do with the set , It preserves the property that a set cannot have duplicate members ,
But the difference is , Elements in an ordered set can be ordered . But it and the list use index subscripts as
The sorting is based on , It sets a score for each element (score) As a sort by
According to the . Pictured 2-24 Shown , The ordered set contains kris、mike、frank、tim、martin、tom,
Their scores are 1、91、200、220、250、251, Ordered sets provide access to specified
Score and element range query 、 Calculate member ranking and other functions , Make good use of ordered sets , Can help
We solve many problems in actual development .

Elements in an ordered set cannot be repeated , however score Can be repeated , Just like the same class

Student number cannot be repeated , But test scores can be the same .
surface 2-7 Gives a list of 、 aggregate 、 The similarities and differences of ordered set . 

2.6.1  command
This section still introduces the commands of ordered collection according to the two dimensions inside and outside the collection .
1. Within collection
(1) Add members
zadd key score member [score member ...]
Next, move to an ordered set user:ranking Add users tom And his score 251:
127.0.0.1:6379> zadd user:ranking 251 tom
(integer) 1
The returned result represents the number of members successfully added :
127.0.0.1:6379> zadd user:ranking 1 kris 91 mike 200 frank 220 tim 250 martin
(integer) 5
of zadd There are two points to note about the order :
·Redis3.2 by zadd The command is added nx、xx、ch、incr Four options :
·nx:member Must not exist , Can be set successfully , Used to add .
·xx:member There must be , Can be set successfully , Used to update the .
·ch: Return after this operation , The number of elements and fractions of an ordered set that have changed
·incr: Yes score Do increase , Equivalent to the following zincrby.

· Ordered sets provide sort fields compared to sets , But there are costs ,zadd Time for
The complexity is O(log(n)),sadd The time complexity of is O(1).
(2) Count the number of members
zcard key
For example, the following operation returns an ordered collection user:ranking The number of members of 5, And collection types
scard command ,zcard The time complexity of is O(1).
127.0.0.1:6379> zcard user:ranking
(integer) 5
(3) Calculate the score of a member
zscore key member
tom The score of is 251, If the member does not exist, return nil:
127.0.0.1:6379> zscore user:ranking tom
"251"
127.0.0.1:6379> zscore user:ranking test
(nil)
(4) Calculate the ranking of members
zrank key member
zrevrank key member
zrank It's from low score to high score ,zrevrank conversely . For example, in the following operation ,tom
stay zrank and zrevrank Ranked No 5 And the 0( from 0 Start calculating ).

127.0.0.1:6379> zrank user:ranking tom
(integer) 5
127.0.0.1:6379> zrevrank user:ranking tom
(integer) 0
(5) Delete members
zrem key member [member ...]
The following operation will make the member mike From an orderly collection user:ranking Delete in .
127.0.0.1:6379> zrem user:ranking mike
(integer) 1
The return result is the number of successful deletions .
(6) Increase the score of members
zincrby key increment member
Here's how to do it tom Added 9 branch , The score becomes 260 branch :
127.0.0.1:6379> zincrby user:ranking 9 tom
"260"
(7) Returns the member of the specified ranking range
zrange key start end [withscores]
zrevrange key start end [withscores]
An ordered set is ranked according to the score ,zrange It goes from low to high ,zrevrange conversely .
The following code returns the lowest ranking of the three members , If you add withscores Options , At the same time, they will return to
Back to the member's score :

127.0.0.1:6379> zrange user:ranking 0 2 withscores
1) "kris"
2) "1"
3) "frank"
4) "200"
5) "tim"
6) "220"
127.0.0.1:6379> zrevrange user:ranking 0 2 withscores
1) "tom"
2) "260"
3) "martin"
4) "250"
5) "tim"
6) "220"
(8) Returns the member of the specified score range
zrangebyscore key min max [withscores] [limit offset count]
zrevrangebyscore key max min [withscores] [limit offset count]
among zrangebyscore Return by score from low to high ,zrevrangebyscore conversely . for example
The following operations return from low to high 200 To 221 Members of the division ,withscores Options return each at the same time
Member's score .[limit offset count] Options can limit the starting position and number of outputs :
127.0.0.1:6379> zrangebyscore user:ranking 200 tinf withscores
1) "frank"
2) "200"
3) "tim"
4) "220"
127.0.0.1:6379> zrevrangebyscore user:ranking 221 200 withscores
1) "tim"
2) "220"
3) "frank"
4) "200"
meanwhile min and max Also supports open interval ( parentheses ) And closed interval ( brackets ),-inf and
+inf They represent infinitesimally small and infinitesimally large :
127.0.0.1:6379> zrangebyscore user:ranking (200 +inf withscores
1) "tim"
2) "220"
3) "martin"
4) "250"
5) "tom"
6) "260" 

(9) Returns the number of members of the specified score range
zcount key min max
The following operation returns to 200 To 221 The number of members of the division :
127.0.0.1:6379> zcount user:ranking 200 221
(integer) 2
(10) Deletes the ascending element in the specified ranking
zremrangebyrank key start end
Next, delete the second start To the first end Members of :
127.0.0.1:6379> zremrangebyrank user:ranking 0 2
(integer) 3
(11) Deletes the member of the specified score range
zremrangebyscore key min max
The following operation will 250 Delete all members with scores above , The return result is the number of successful deletions :
127.0.0.1:6379> zremrangebyscore user:ranking (250 +inf
(integer) 2
2. Operations between sets
Map 2-25 Two ordered sets of are imported into Redis in .

127.0.0.1:6379> zadd user:ranking:1 1 kris 91 mike 200 frank 220 tim 250 martin
251 tom
(integer) 6
127.0.0.1:6379> zadd user:ranking:2 8 james 77 mike 625 martin 888 tom
(integer) 4
(1) intersection
zinterstore destination numkeys key [key ...] [weights weight [weight ...]]
[aggregate sum|min|max]
This command has many parameters , Here are the instructions :
·destination: The intersection calculation is saved to this key .
·numkeys: You have to do the intersection to calculate the number of keys .
·key[key...]: The key that needs to do the intersection computation .

·weights weight[weight...]: The weight of each key , When you do the intersection calculation , In each key
Each member I'm going to multiply my score by this weight , The weight of each key is by default 1.
·aggregate sum|min|max: After the member intersection is calculated , The score can be calculated by sum( and )、
min( minimum value )、max( Maximum ) Make a summary , The default value is sum.
The following operation is right user:ranking:1 and user:ranking:2 Do intersection ,weights and
aggregate Default configuration used , You can see the target key user:ranking:1_inter_2 On the score
Did sum operation :
127.0.0.1:6379> zinterstore user:ranking:1_inter_2 2 user:ranking:1
user:ranking:2
(integer) 3
127.0.0.1:6379> zrange user:ranking:1_inter_2 0 -1 withscores
1) "mike"
2) "168"
3) "martin"
4) "875"
5) "tom"
6) "1139"
If you want to let user:ranking:2 The weight of is changed to 0.5, And the aggregation effect uses max, Sure
Do the following :
127.0.0.1:6379> zinterstore user:ranking:1_inter_2 2 user:ranking:1
user:ranking:2 weights 1 0.5 aggregate max
(integer) 3
127.0.0.1:6379> zrange user:ranking:1_inter_2 0 -1 withscores
1) "mike"
2) "91"
3) "martin"
4) "312.5"
5) "tom"
6) "444"
(2) Combine
zunionstore destination numkeys key [key ...] [weights weight [weight ...]]
[aggregate sum|min|max]

All the parameters of the command and zinterstore It's consistent , It's just doing union computation , for example
The next operation is to calculate user:ranking:1 and user:ranking:2 Union ,weights and
aggregate Default configuration used , You can see the target key user:ranking:1_union_2 On the score
Did sum operation :
127.0.0.1:6379> zunionstore user:ranking:1_union_2 2 user:ranking:1
user:ranking:2
(integer) 7
127.0.0.1:6379> zrange user:ranking:1_union_2 0 -1 withscores
1) "kris"
2) "1"
3) "james"
4) "8"
5) "mike"
6) "168"
7) "frank"
8) "200"
9) "tim"
10) "220"
11) "martin"
12) "875"
13) "tom"
14) "1139"
So far, the command of ordered set is basically finished , surface 2-8 It's the time complexity of these commands ,
When developers use the corresponding commands for development , It's not just about functionality , Also understand the corresponding
Time complexity of , To prevent the application side from reducing efficiency due to improper use and Redis Blocking .

surface 2-8 The time complexity of ordered set commands

 

 2.6.2  Internal encoding
There are two kinds of internal codes for ordered set types :
·ziplist( Compressed list ): When the number of elements in an ordered set is less than zset-max-ziplist-
entries To configure ( Default 128 individual ), At the same time, the value of each element is less than zset-max-ziplist-value with
Set up ( Default 64 byte ) when ,Redis Will use ziplist As an internal implementation of an ordered set ,ziplist
Can effectively reduce the use of memory .
·skiplist( Skip list ): When ziplist When the conditions are not met , Ordered sets will use skiplist do
For internal implementation , Because at this time ziplist The efficiency of reading and writing will decrease .
Here is an example to illustrate :
1) When the number of elements is small and each element is small , The internal code is skiplist:
127.0.0.1:6379> zadd zsetkey 50 e1 60 e2 30 e3
(integer) 3
127.0.0.1:6379> object encoding zsetkey
"ziplist"
2.1) When the number of elements exceeds 128 individual , The internal code becomes ziplist:
127.0.0.1:6379> zadd zsetkey 50 e1 60 e2 30 e3 12 e4 ... Ignore ... 84 e129
(integer) 129
127.0.0.1:6379> object encoding zsetkey
"skiplist"
2.2) When an element is greater than 64 Byte time , The internal code will also become hashtable:
127.0.0.1:6379> zadd zsetkey 20 "one string is bigger than 64 byte.............
..................."
(integer) 1
127.0.0.1:6379> object encoding zsetkey
"skiplist"

2.6.3  Use scenarios
A typical use scenario of ordered set is leaderboard system . For example, video websites need to be used
Make a ranking list of videos uploaded by users , The dimensions of the list can be many : According to the time 、 Follow the broadcast
Release quantity 、 According to the number of likes . This section uses the like dimension , Record the videos uploaded by users every day
The list of . We mainly need to achieve the following 4 Features .
(1) Add user likes
For example, users mike Uploaded a video , And got it. 3 A great , You can use an ordered set of
zadd and zincrby function :
zadd user:ranking:2016_03_15 mike 3
If you get a compliment later , have access to zincrby:
zincrby user:ranking:2016_03_15 mike 1
(2) Cancel user likes
For various reasons ( For example, the user logs off 、 Users cheat ) The user needs to be deleted , At this time need
Remove users from the list , have access to zrem. For example, delete members tom:
zrem user:ranking:2016_03_15 mike
(3) Show the top ten users who got the most likes
This function uses zrevrange Command implementation :

zrevrangebyrank user:ranking:2016_03_15 0 9
(4) Show user information and user scores
This function uses the user name as the key suffix , Save user information in hash type , As for users
Scores and rankings can be used zscore and zrank Two functions :
hgetall user:info:tom
zscore user:ranking:2016_03_15 mike
zrank user:ranking:2016_03_15 mike

原网站

版权声明
本文为[Gu Ge academic]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042229263955.html