Article directory
[Redis01] Redis common commands
1. Basic commands
1. ping (heartbeat command)
Type the ping command. If you see a PONG response, it means that the connection between the client and Redis is normal.
2. get/set (read and write key-value commands)
set key value
The specified willkey-value
be written to DB.get key
The value of the specified key will be read.
3. select (switch database)
Redis has 16 databases by default. This can be seen visually in the Redis Desktop Manager (RDM) graphical client. By default, DB No. 0 is used, and the DB can be switched by selecting the db index. As shown in the figure, switch to DB No. 1:
4. dbsize (check the number of keys)
The dbsize command can view the number of keys in the current database.
5. flushdb (delete all data in the current database)
Clear all data in the current DB without affecting other DBs.
6. flushall (delete all data in DB)
2. Key related operation commands
1、keys
Format: KEYS pattern
Function: Find all keys matching the given pattern pattern, pattern is a regular expression.
Note: KEYS is very fast, but using it in a large database may block the service of the current server. Therefore, this command is generally not used in the production environment, and the scan command is used instead.
As shown in the figure: view all modes and view all modes beginning with 'a' at the end
2、exists
Format: EXISTS key
Function: Check if the given key exists.
Description: If the key exists, return 1, otherwise return 0.
3、of
Format: DEL key [key ...]
Function: Delete one or more given keys. Keys that do not exist are ignored.
Description: Return the number of deleted keys.
4、rename
l Format: RENAME key newkey
l Function: Rename the key to newkey.
l Description: When the key is the same as newkey, or the key does not exist, an error will be returned. When newkey already exists, the RENAME command will overwrite the old value. It prompts OK when the name is changed successfully, and returns an error when it fails.
5、move
l Format: MOVE key db
l Function: Move the key of the current database to the given database db.
l Description: If the current database (source database) and the given database (target database) have a given key with the same name, or the key does not exist in the current database, then MOVE has no effect. Returns 1 if the move was successful, and 0 if it failed.
6、type
l Format: TYPE key
l Function: Return the type of the value stored in the key.
l Description: There are the following six return values
none (key does not exist)
string (string)
list (list)
set (collection)
zset (ordered set)
hash (hash table)
7、expire/pexpire
l Format: EXPIRE key seconds
l Function: Set the lifetime for a given key. When the key expires (time to live is 0), it is automatically deleted. The time unit of expire is seconds, and the time unit of pexpire is milliseconds. In Redis, a key with a lifetime is called "volatile".
l Note: The survival time setting returns 1 successfully. Returns 0 if the key does not exist. The rename operation does not change the lifetime of the key.
8、ttl/pttl
Format: TTL key
Function: TTL, time to live, returns the remaining time to live for a given key.
Note: There are three possible return values:
1/ When the key does not exist, return -2.
2/ When the key exists but the remaining lifetime is not set, return -1.
3/ Otherwise, return the remaining lifetime of the key. The ttl command returns time units in seconds, and the pttl command returns time units in milliseconds.
9、persist
l Format: PERSIST key
l Function: Remove the lifetime of a given key, and convert this key from "volatile" to "durable".
l Description: When the time-to-live is removed successfully, it returns 1; if the key does not exist or the key does not have a time-to-live, it returns 0.
10、randomkey
l Format: RANDOMKEY
l Function: Randomly return (not delete) a key from the current database.
l Description: When the database is not empty, return a key. Returns nil when the database is empty.
11、scan
-
格式:SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]
-
Function: used to iterate over the database keys in the database. The meaning of each option is:
- cursor: The cursor at the start of this iteration.
- pattern : The pattern of the key to be matched in this iteration.
- count : How many elements to return from the dataset in this iteration, the default value is 10.
- type: The type of value to be returned in this iteration, defaulting to all types.
The SCAN command is a cursor-based iterator: each time the SCAN command is called, it will return an array containing two elements to the user, the first element is a new cursor for the next iteration, and the second The elements are an array, which contains all the elements being iterated. The user needs to use this new cursor as the cursor parameter of the SCAN command in the next iteration, so as to continue the previous iteration process. When the cursor parameter of the SCAN command is set to 0, the server will start a new iteration. If the new cursor returns 0, the iteration is over.
-
Description: Incremental iteration with intermittent, negative, out-of-range, or other abnormal cursors will not crash the server.
When the amount of data is large, the specification of count may not work, and Redis will automatically adjust the number of traversals each time. Since the scan command only returns a small number of elements each time it is executed, this command can be used in a production environment without the server blocking problem caused by the KEYS command.
The algorithm used by the incremental iteration command only guarantees that the iteration will stop when the size of the data set is bounded. In other words, if the size of the iterated data set continues to grow, the incremental iteration command may never stop. Unable to complete a full iteration. That is, when a data set is getting bigger and bigger, more and more work needs to be done to access all the elements in the data set. Whether an iteration can end depends on whether the speed at which the user executes the iteration is faster than the speed at which the data set grows. quick.
-
Related commands: There are also three scan commands for traversing the three types of value.
- hscan: belongs to the set of Hash-type Value operation commands, used to traverse all field-value pairs of the specified Hash table in the current db.
- sscan: belongs to the set of Set type Value operation commands, used to traverse all elements of the specified set collection in the current db
- zscan: belongs to the ZSet type Value operation command set, used to traverse all the elements (value and element value) of the specified ordered set in the current db
3. String type Value operation command
The Value of Redis stored data can be a String type data. Value of String type is the most basic and common type in Redis. Any data can be stored in Value of String type, including numeric or even binary pictures, audio, video, serialized objects, etc. The maximum size of a String type Value is 512M.
1、set
格式:SET key value [EX seconds | PX milliseconds] [NX|XX]
Function: In addition to directly setting the value of key as value, SET can also specify some parameters.
EX seconds: Set the expiration time for the current key, in seconds. Equivalent to the SETEX command.
PX milliseconds: Set the expiration time for the current key, in milliseconds. Equivalent to the PSETEX command.
NX: The specified key will only be set successfully if it does not exist. It is used to add the specified key. Equivalent to SETNX command.
XX: The specified key must exist to be set successfully, and is used to update the value of the specified key.
Note: If there is a space in the value string, the string needs to be enclosed in double quotes or single quotes, otherwise it will be considered that the number of parameters of the set command is incorrect and an error will be reported.
2、setex/psetex
Format: SETEX/PSETEX key seconds value
Function: set expire, which not only specifies the value for the key, but also sets the survival time for it. The unit of setex is seconds, and the unit of psetex is milliseconds.
Description: If the key already exists, the old value will be overwritten. This command is similar to the following two commands. The difference is that SETEX is an atomic operation, and the two actions of associating the value and setting the lifetime will be completed at the same time. This command is very practical when Redis is used as a cache.
SET key value
EXPIRE key seconds # Set the survival time
As shown in the figure below, the two commands have the same effect:
3、setnx
l Format: SETNX key value
l Function: SET if Not eXists, set the value of the key to value if and only if the key does not exist. If the given key
already exists, SETNX does nothing. If successful, return 1, otherwise, return 0.
l Description: This command is equivalent to
set key value nx
4、getset
Format: GETSET key value
Function: Set the value of the given key to value, and return the old value of the key.
Description: When the key exists but is not a string type, return an error; when the key does not exist, return nil.
5、mset/msetnx
Format: MSET/MSETNX key value [key value …]
Function: Set one or more key-value pairs at the same time.
Note: If a given key already exists, MSET will overwrite the original old value with the new value. If this is not what you want, please consider using the MSETNX command: it will only be used when all given keys do not exist. In this case, perform the setting operation. MSET/MSETNX is an atomic operation. All given keys will be set at the same time. It is impossible for some given keys to be updated while others remain unchanged. The command never fails.
6、mget
Format: MGET key [key ...]
Function: Return all (one or more) values of the given key.
Explanation: If a certain key does not exist in the given key, then this key returns the special value nil. Therefore, the command never fails.
7、append
Format: APPEND key value
Function: If the key already exists and is a character string, the APPEND command will append the value to the end of the original value of the key. If the key does not exist, APPEND simply sets the given key to the value, just like executing SET key value.
Description: After appending value, the length of the string in key.
8、incr/decr
Format: INCR key or DECR key
Function: increment, auto-increment. Increments the numeric value stored in key by one. decrement, automatic decrement. Decrements the numeric value stored in key by one.
Note: If the key does not exist, the value of the key will be initialized to 0 first, and then the increment/decrement operation will be performed. Returns an error if the value cannot be represented as a number. If executed correctly, returns the incremented/decremented value.
9、incrby/decrby
Format: INCRBY key increment or DECRBY key decrement
Function: Increase/decrease the specified value of the digital value stored in the key, this value can only be an integer, it can be a negative number, but it cannot be a decimal.
Note: If the key does not exist, the value of the key will be initialized to 0 first, and then the increase/decrease operation will be performed. Returns an error if the value cannot be represented as a number. If done correctly, returns the incremented/decremented value.
10、incrbyfloat
Format: INCRBYFLOAT key increment
Function: add the floating-point number increment to the value stored in the key.
Instructions: Same instructions as before. There is no decrbyfloat command, but the negative value of increment can achieve the effect of subtraction.
11、strlen
Format: STRLEN key
Function: Return the length of the string value stored in key.
Description: When the key does not store a string value, return an error; when the key does not exist, return 0.
12、tight
Format: GETRANGE key start end
Function: Return the substring of the string value in the key, the interception range of the string is determined by the two offsets of start and end, including start and end.
Note: end must be greater than start. Negative offsets are supported, which means counting from the end of the string, -1 means the last character, -2 means the penultimate character, and so on.
13、setrange
Format: SETRANGE key offset value
Function: Replace the string value str stored by the given key with the value parameter, starting from the offset offset.
Note: When the offset value is greater than the length of str, the middle is filled with zero bytes \x00, that is, 0000 0000 bytes are filled; the non-existing key is treated as an empty string.
14. Bit operation command
The commands containing BIT in the name are commands for operating on binary bits, for example, setbit, getbit, bitcount, bittop, bitfield, these commands are not commonly used.
15. Typical application scenarios
There are many application scenarios where Value is of String type. Here are just examples of such typical application scenarios:
-
Data cache: Redis is used as the data cache layer, and MySQL is used as the data storage layer. The application server first obtains data from Redis. If there is no data in the cache layer, the data is obtained from MySQL, stored in the cache layer, and then returned to the application server.
-
Counter: Write a key whose value is a numeric value in Redis as a platform counter, video playback counter, etc. Every time a valid client visits, or every time a video is played, the counter in Redis is directly modified, and then persisted to other data sources in an asynchronous manner, such as MySQL.
-
Shared Session: For a distributed application system, if session data such as user login information is saved in the server that provides login services, then if the user submits requests such as favorites and payments again, problems may occur: when providing favorites, The server of payment and other services does not have the session data of the user, so the user needs to log in again. For users, this is unacceptable. At this point, all the session data of all users in the system can be saved in Redis. After the user submits a new request, the system will first search for the corresponding session data in Redis. If it exists, then perform related operations, otherwise jump to log in page. This way it doesn't raise the "re-login" problem.
-
Speed limiter: In order to prevent DoS (Denial of Service, denial of service) attacks, many platforms generally restrict an IP from visiting more than n times in one second. And Redis can combine the expiration time of the key and the incr command to complete the speed limit function and act as a speed limiter. Note that it cannot prevent DDoS (Distributed Denial of Service) attacks.
4. Hash type Value operation command
The Value of Redis data storage can be a Hash type. The Hash type is also called Hash table, dictionary, etc.
The Hash table is a mapping table Map, which is also composed of key-value pairs. In order to distinguish it from the overall key, the key here is called field, and the value is called value. Note that the field-value pairs in the Hash table of Redis are all of type String.
1、hset
Format: HSET key field value
Function: Set the value of the field field in the hash table key to value.
Description: If the key does not exist, a new hash table is created and HSET is performed . If the field field already exists in the hash table, the old value will be overwritten. Returns 1 if field is a new field in the hash table and the value is set successfully. Returns 0 if the field already exists in the hash table and the old value has been overwritten by the new value.
2、hget
Format: HGET key field
Function: Return the value of the given field field in the hash table key.
Description: When the given domain does not exist or the given key does not exist, return nil.
3、hmset
Format: HMSET key field value [field value ...]
Function: Set multiple field-value (field-value) pairs to the hash table key at the same time.
Description: This command overwrites existing fields in the hash table. If the key does not exist, an empty hash table is created and the HMSET operation is performed. If the command is executed successfully, return OK. Returns an error when key is not of hash type.
4、hmget
Format: HMGET key field [field ...]
Function: Return the values of one or more fields in the hash table key in the given order.
Description: Returns a nil value if the given field does not exist in the hash table. Since a non-existent key is treated as an empty hash table, an HMGET operation on a non-existent key will return a table with only nil values.
5、hgetall
Format: HGETALL key
Function: Return all fields and values in the hash table key.
Explanation: In the return value, immediately after each domain name (field name) is the value of the field (value), so the length of the return value is twice the size of the hash table. If key does not exist, returns an empty list. If the key contains a large number of elements, this command may block the Redis service. Therefore, this command is generally not used in the production environment, and the hscan command is used instead.
6、hsetnx
Format: HSETNX key field value
Function: Set the value of the field field in the hash table key to value, if and only if the field field does not exist.
Note: If the field field already exists, this operation is invalid. If the key does not exist, a new hash table is created and the HSETNX command is executed.
7、hdel
Format: HDEL key field [field ...]
Function: Delete one or more specified domains in the hash table key, and the non-existing domains will be ignored.
Description: Returns the number of successfully removed domains, excluding ignored domains.
8、hexists
Format: HEXISTS key field
Function: Check whether the given field field exists in the hash table key.
Description: Returns 1 if the hash table contains the given field. Returns 0 if the given field does not exist, or if the key does not exist.
9、hincrby/hincrbyfloat
Format: HINCRBY key field increment
Function: add increment to the value of the field field in the hash table key. The hincrby command can only increment integer values, while hincrbyfloat can increment fractional values.
Note: The increment can also be a negative number, which is equivalent to the subtraction operation on the given field. If the key does not exist, a new hash table is created and the HINCRBY command is executed. If the field field does not exist, then the value of the field is initialized to 0 before executing the command. Executing the HINCRBY command on a field that stores string values will cause an error.
10、hkeys/whales
Format: HKEYS key or HVALS key
Function: Return all fields/values in the hash table key.
Description: When the key does not exist, return an empty table.
11、arrived
Format: HLEN key
Function: Return the number of domains in the hash table key.
Description: When the key does not exist, return 0.
12、hstrlen
Format: HSTRLEN key field
Function: Return the string length (string length) of the value associated with the given domain field in the hash table key.
Description: If the given key or field does not exist, the command returns 0.
13. Application scenarios
Hash type Value is very suitable for storing object data. The key is the name of the object, and the value is the Map describing the properties of the object. The modification of the properties of the object can be done directly in Redis. It is not like a String-type Value storage object, that object is serialized, such as serialized into a JSON string, the modification of the object property value needs to be deserialized into an object before modification, and then serialized into a JSON string after modification Write to Redis.
5. List type Value operation command
The Value of Redis stored data can be a String list type data. That is, each element in the list is String type data. The data in the list will be sorted in the order of insertion. However, the bottom layer of the list is actually a doubly linked list without a head node, so the operation performance on the head and tail of the list is high, but the performance on the insertion and deletion of intermediate elements is relatively poor.
1、lpush/rpush
格式:LPUSH key value [value …] 或 RPUSH key value [value …]
Function: Insert one or more values value into the header/footer of the list key (the header is on the left and the tail is on the right)
Note: If there are multiple values, for lpush, each value will be inserted into the table header in order from left to right; for rpush, each value will be inserted in order from left to right at the end of the table . If the key does not exist, an empty list is created and the operation performed. Returns an error when key exists but is not a list type. Returns the length of the list on success.
2、curtain
Format: LLEN key
Function: Return the length of the list key.
Description: If key does not exist, key is interpreted as an empty list and 0 is returned. Returns an error if key is not a list type.
3、line index
Format: LINDEX key index
Function: Return the element whose subscript is index in the list key. Lists are counted from 0.
Explanation: If the value of the index parameter is not within the range of the list (out of range), return nil.
4、lset
Format: LSET key index value
Function: Set the value of the element whose key subscript is index in the list to value.
Description: An error is returned when the index parameter is out of range, or when LSET is performed on an empty list (key does not exist).
5、lrange
Format: LRANGE key start stop
Function: Return the elements in the specified interval [start, stop] in the list key, which includes two endpoints.
Explanation: The subscript of List starts from 0, that is, 0 represents the first element of the list, 1 represents the second element of the list, and so on. Negative subscripts can also be used, with -1 representing the last element of the list, -2 representing the second-to-last element of the list, and so on. Out-of-range subscript values do not cause an error. If the start index is greater than the list's largest index, then LRANGE returns an empty list. If the stop subscript is larger than the maximum subscript, Redis sets the value of stop to the maximum subscript.
6、lpushx/rpushx
Format: LPUSHX key value or RPUSHX key value
Function: Insert the value value into the header/footer of the list key, if and only if the key exists and is a list.
Description: When the key does not exist, the command does nothing. If the execution is successful, the length of the table is output.
7、lensed
Format: LINSERT key BEFORE|AFTER pivot value
Function: Insert the value value into the list key, before or after the element pivot.
Description: When the pivot element does not exist in the list, no operation is performed and -1 is returned; when the key does not exist, the key is regarded as an empty list, no operation is performed and 0 is returned; if the key is not a list type, one is returned Error; if the command succeeds, returns the length of the list after the insert operation is complete.
8、lpop/rpop
Format: LPOP key [count] or RPOP key [count]
Function: Remove count elements from the head/tail of the list key, and return the removed elements. count default value 1
Description: When the key does not exist, return nil
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-uPdTzGAT-1681219408332)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230410200826128.png)]
9、blpop/brpop
Format: BLPOP key [key …] timeout or BRPOP key [key …] timeout
Function: BLPOP/BRPOP is a blocking popup command for the list. They are blocking versions of LPOP/RPOP commands. When there is no element available for popping in the given list, the connection will be blocked by BLPOP/BRPOP command until the waiting timeout times out or an element that can be popped is found. When multiple key parameters are given, each list is checked in sequence according to the order of the parameter keys, and the head element of the first non-empty list is popped up. timeout is the blocking duration, in seconds, if its value is 0, it means that as long as there is no pop-up element, it will always block.
Explanation: If no element is popped up within the specified time, return a nil and the waiting time. Otherwise, return a list with two elements, the first element is the key to which the popped element belongs, and the second element is the value of the popped element.
The instruction introduces in detail: Redis Daily Practice (26): BLPOP and BRPOP Commands - Motianlun (modb.pro)
10、rpoplpush
Format: RPOPLPUSH source destination
Function: Command RPOPLPUSH to perform the following two actions within an atomic time:
- Pop the last element (tail element) in the list source and return it to the client.
- Insert the popped-up element from source into the destination list as the head element of the destination list. If source does not exist, the value nil is returned and no other action is performed. If source and destination are the same, the element at the end of the list is moved to the head, and that element is returned. This special case can be thought of as a rotation operation on the list.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-GhNRwCLj-1681218054418)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230410201242354.png)]
11、brpoplpush
Format: BRPOPLPUSH source destination timeout
Function: BRPOPLPUSH is a blocking version of RPOPLPUSH. When the given list source is not empty, BRPOPLPUSH behaves the same as RPOPLPUSH. When the list source is empty, the BRPOPLPUSH command blocks the connection until it times out, or until another client executes an LPUSH or RPUSH command on source. timeout is the blocking duration, in seconds, if its value is 0, it means that as long as there is no pop-up element, it will always block.
Explanation: If no element is popped up within the specified time, return a nil and the waiting time. Otherwise, return a list with two elements, the first element is the value of the popped element, and the second element is the waiting time.
As shown in the figure: the nums list is empty [the transfer of the external link image failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-fsjQiqNt-1681218054418) (https://typora-1259159092.cos.ap- nanjing.myqcloud.com/typora/image-20230410201459060.png)]
12、lrem
Format: LREM key count value
Function: According to the value of the parameter count, remove the elements in the list that are equal to the parameter value. The value of count can be one of the following:
- count > 0 : Search from the head to the end of the table, remove elements equal to value, the number is count.
- count < 0 : Search from the end of the table to the head of the table, remove elements equal to value, the number is the absolute value of count.
- count = 0 : Remove all values equal to value from the table.
Description: Returns the number of elements removed. When the key does not exist, the LREM command returns 0, because the key that does not exist is regarded as an empty list (empty list).
The lls list in the figure does not exist:
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-i1kldKKZ-1681218054419)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230410202033415.png)]
13、ltrim
Format: LTRIM key start stop
Function: Trim a list, that is to say, let the list only keep the elements in the specified range, and the elements not in the specified range will be deleted.
Explanation: The subscript (index) parameters start and stop are based on 0, that is to say, 0 represents the first element of the list, 1 represents the second element of the list, and so on. Negative subscripts can also be used, with -1 representing the last element of the list, -2 representing the second-to-last element of the list, and so on. Returns an error when key is not a list type. If the start subscript is greater than the list's largest subscript end (LLEN list minus 1), or if start > stop, LTRIM returns an empty list because LTRIM has already emptied the entire list. If the stop subscript is larger than the end subscript, Redis will set the value of stop to end.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-ux6oXHR2-1681218054419)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230410202145481.png)]
14. Application scenarios
There are many application scenarios where the Value is a List type, mainly through building different data structures to realize corresponding business functions. Here we only summarize the implementation methods of these data structures, without giving specific examples.
(1) stack
The stack data structure effect can be realized through lpush + lpop: first in last out. Insert data from the left side of the list through lpush, and remove data from the left side of the list through lpop. Of course, the same effect can also be achieved through rpush + rpop, but the operation is on the right side of the list.
(2) queue
The queue data structure effect can be realized through lpush + rpop: first in first out. Insert data from the left side of the list through lpush, and remove data from the right side of the list through rpop. Of course, the same effect can also be achieved through rpush + lpop, but the direction of operation is just opposite.
(3) Blocking message queue
The blocking message queue effect can be achieved through lpush + brpop. The client as a message producer uses lpush to insert data from the left side of the list, and multiple clients as a message consumer use brpop blocking to "preempt" the tail data of the list for consumption, ensuring load balancing and high availability of consumption. The timeout of brpop is set to 0, which means that as long as there is no data to pop, it will be blocked forever.
(4) Dynamic finite sets
Limited collections can be achieved through lpush + ltrim. Add data to the list from the left of the list by lpush, and keep the dynamic finiteness of the collection by ltrim. Dynamic management such as the elimination of the bottom of the enterprise and the key classes of the school can be realized through this dynamic limited set. Of course, the same effect can also be achieved through rpush + ltrim, but the direction of operation is just the opposite.
6. Set type Value operation command
The Value of Redis data storage can be a Set collection, and each element in the collection is of String type. Set is very similar to List, but the difference is that elements in Set are disordered and non-repeatable, while List is orderly and repeatable.
The implementation of the Set collection in Redis is similar to that in Java, and its bottom layer is a hash table whose value is null. It is precisely because of this that disorder and non-repeatability are caused.
1、sadd
Format: SADD key member [member ...]
Function: Add one or more member elements to the set key, which already exists in the set member
element will be ignored.
Explanation: If the key does not exist, create a collection containing only member elements as members. Returns an error when key is not a collection type.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-HZ9aKIX8-1681218054420)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411192311511.png)]
2、smembers
Format: SMEMBERS key
Function: Return all members in the set key.
Note: A key that does not exist is considered an empty collection. If the key contains a large number of elements, this command may block the Redis service. Therefore, this command is generally not used in the production environment, and the sscan command is used instead.
3、scard
Format: SCARD key
Function: Return the length of the Set collection
Description: When the key does not exist, return 0.
4、sismember
Format: SISMEMBER key member
Function: Determine whether the member element is a member of the set key.
Description: Returns 1 if the member element is a member of the collection. Returns 0 if the member element is not a member of the set, or key does not exist.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-By00Kd5B-1681218054422)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411192658608.png)]
5、smove
Format: SMOVE source destination member
Function: Move the member element from the source collection to the destination collection.
Description: If the source collection does not exist or does not contain the specified member element, the SMOVE command does nothing and returns 0. Otherwise, the member element is removed from the source collection and added to the destination collection, and 1 is returned. When the destination collection already contains member elements, the SMOVE command simply deletes the member elements in the source collection. Returns an error when source or destination is not a collection type.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-HeIqQuCP-1681218054422)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411192802656.png)]
6、srem
Format: SREM key member [member ...]
Function: Remove one or more member elements in the set key, the non-existing member elements will be ignored, and return the number of successfully removed elements.
Description: When the key is not a collection type, an error is returned.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-tzXDyhRW-1681218054423)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411192926406.png)]
7、srandmember
Format: SRANDMEMBER key [count]
Function: Return count random elements in the collection. The default value of count is 1.
Explanation: If count is a positive number and less than the length of the collection, then return an array containing count elements, and the elements in the array are different. If count is greater than or equal to the collection length, then the entire collection is returned. If count is negative, returns an array containing the absolute value of count elements, but elements in the array may appear duplicated.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-fgiGBRJ3-1681218054423)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411193102935.png)]
8、spop
Format: SPOP key [count]
Function: Remove and return count random elements in the collection. count must be positive and defaults to 1.
Description: If count is greater than or equal to the collection length, then remove and return the entire collection.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-5OJ7lWtL-1681218054424)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411193320299.png)]
9、sdiff/sdiffstore
Format: SDIFF key [key ...] or SDIFFSTORE destination key [key ...]
Function: Return the difference between the first set and other sets. Difference set, difference.
Explanation: The difference between these two commands is that sdiffstore can not only display the difference, but also store the difference in the specified set destination. If the destination collection already exists, it is overwritten. A key that does not exist is considered an empty set.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-sH710fKh-1681218054425)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411193446264.png)]
10、sinter / sinterstore
Format: SINTER key [key ...] or SINTERSTORE destination key [key ...]
Function: Return the intersection between multiple collections. Intersection, intersection.
Explanation: The difference between these two commands is that sinterstore can not only display the intersection, but also store the intersection in the specified collection destination. If the destination collection already exists, it is overwritten. A key that does not exist is considered an empty set.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-aW2vfO9Z-1681218054425)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411193629443.png)]
11、sunion/sunionstore
Format: SUNION key [key ...] or SUNIONSTORE destination key [key ...]
Function: Return the union between multiple collections. Union.
Explanation: The difference between these two commands is that sunionstore can not only display the union, but also store the union in the specified collection destination. If the destination collection already exists, it is overwritten. A key that does not exist is considered an empty set.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-OuJUo2Qc-1681218054426)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411193825086.png)]
12. Application scenarios
(1) Dynamic blacklist
For example, a blacklist for access control needs to be set in a server. If the blacklist is directly written into the configuration file of the server, the problem is that the blacklist cannot be dynamically modified. At this time, the blacklist can be directly written into Redis. As long as there is a client to access the server, the server will first check whether the IP exists in the Redis blacklist after obtaining the client IP. If it exists, the access will be denied, otherwise the access will pass. .
(2) Limited random number
The limited random number means that the returned random number is based on a random number within a certain set range, such as lottery and random selection. Through spop or srandmember, elements can be randomly selected from the specified collection.
(3) User portrait
Various platforms such as social platforms and e-commerce platforms that require users to register and log in will make portraits for each user based on the information provided by the user and the user's usage habits, that is, define many tags for each user that can reflect the characteristics of the user. The tag can be added to the collection corresponding to the user using sadd. These tags are unordered and non-repetitive.
At the same time, the platform can also use sinter/sinterstore to recommend friends, products, and customers based on the intersection of user portraits.
7. Ordered Set-type Value operation command
The Value of Redis data storage can be an ordered Set, and each element in this ordered Set is of String type. The difference between an ordered Set and a Set is that each element in an ordered Set has a score, and Redis will sort the set from small to large according to the value of the score. It has the same requirements as the Set collection, the elements cannot be repeated, but the score of the elements can be repeated. Since all commands of this type begin with the letter z, this Set is also called a ZSet.
1、zadd
格式:ZADD key score member [[score member] [score member] …]
Function: Add one or more member elements and their score values to the appropriate position in the ordered set key.
Description: The score value can be an integer value or a double precision floating point number. If key does not exist, an empty sorted set is created and ZADD is performed. Returns an error when key exists but is not of sorted-set type. If the command succeeds, it returns the number of new members that were successfully added, excluding existing members that were updated. If the member value to be written already exists but the score value is different, the new score value will overwrite the old score.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-6uazNJpi-1681218054426)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411194528792.png)]
2、zrange/zrevrange
Format: ZRANGE key start stop [WITHSCORES] or ZREVRANGE key start stop [WITHSCORES]
Function: Return the members in the specified interval in the ordered set key. The zrange command will sort by increasing score value, and the zrevrange command will sort by decreasing score value. Members with the same score value are sorted lexicographically/reverse-lexicographically. Members can be returned with their score values by using the WITHSCORES option.
Note: The subscript parameter starts from 0, that is, 0 means the first member of the ordered set, 1 means the second member of the ordered set, and so on. You can also use negative subscripts, -1 for the last member, -2 for the second-to-last member, and so on. Out-of-range subscripts do not cause an error. For example, when the value of start is greater than the largest subscript of the sorted set, or start > stop, the ZRANGE command simply returns an empty list. For another example, if the value of the stop parameter is greater than the maximum subscript of the ordered set, then Redis will treat stop as the maximum subscript.
If the specified range in key contains a large number of elements, this command may block the Redis service. Therefore, in the production environment, if you want to query all the elements in the ordered set, you generally do not use this command, but use the zscan command instead.
3、zrangebyscore/zrevrangebyscore
格式:ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
Function: Return all members whose score value is between min and max (including equal to min or max) in the ordered set key. Ordered set members are arranged in increasing/decreasing order of score value. Members with the same score value are sorted lexicographically/reverse-lexicographically. The optional LIMIT parameter specifies the number and range of returned results (like SELECT LIMIT offset, count in SQL). Note that when the offset is large, the operation of locating the offset may need to traverse the entire ordered set, which may be less efficient Low. The optional WITHSCORES parameter determines whether the result set returns the ordered set members alone, or returns the ordered set members and their score values together.
Note: The values of min and max are plus or minus infinity. By default, the value of the interval uses a closed interval (less than or equal to or greater than or equal to), and an optional open interval (less than or greater than) can also be used by adding a left bracket "(" before the parameter.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-6u0RbrYt-1681218054427)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195027560.png)]
4、zcard
Format: ZCARD key
Function: Returns the length of the collection
Description: When the key does not exist, return 0.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-cfDiABPs-1681218054428)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195150576.png)]
5、zcount
Format: ZCOUNT key min max
Function: Return the number of members whose score value is between min and max (including the score value equal to min or max by default) in the ordered set key.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-jJbynJKT-1681218054429)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195252304.png)]
6、zscore
Format: ZSCORE key member
Function: Return the score value of the member member in the ordered set key.
Explanation: If the member element is not a member of the ordered set key, or the key does not exist, return nil.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-VZ1nmMwt-1681218054429)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195405826.png)]
7、zincrby
Format: ZINCRBY key increment member
Function: add increment to the score value of the member member of the ordered set key. The increment value can be an integer value or a double precision floating point number.
Note: You can subtract the corresponding value from the score by passing a negative value increment. When the key does not exist, or the member is not a member of the key, ZINCRBY key increment member is equivalent to ZADD key increment member. Returns an error when key is not of sorted set type. If the command is executed successfully, the new score value of the member member will be returned.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-j9kPl1xO-1681218054430)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195539936.png)]
8、bone/bone
Format: ZRANK key member or ZREVRANK key member
Function: Return the rank of the member member in the ordered set key. The zrank command will sort by increasing score value, and the zrevrank command will sort by score decreasing.
Explanation: The rank of the member with the smallest score value is 0. Returns nil if member is not a member of the sorted set key.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-P5KtHLr8-1681218054430)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195712685.png)]
9、age
Format: ZREM key member [member ...]
Function: Remove one or more members in the ordered set key, and the non-existing members will be ignored.
Description: When the key exists but is not an ordered set type, an error is returned. On success, returns the number of successfully removed members, excluding ignored members.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-j3z0muca-1681218054431)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411195847811.png)]
10、zremrangebyrank
Format: ZREMRANGEBYRANK key start stop
Function: Remove all members in the specified rank interval in the ordered set key.
Explanation: The ranking intervals are indicated by the subscript parameters start and stop, including start and stop. The rank interval parameter starts from 0, ie 0 means the member with the first rank, 1 means the member with the second rank, and so on. Negative numbers can also be used, -1 for the last member, -2 for the second-to-last member, and so on. If the command is executed successfully, the number of removed members will be returned.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-Au1pv6wx-1681218054431)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411200011252.png)]
11、zremrangebyscore
Format: ZREMRANGEBYSCORE key min max
Function: Remove all members whose score value is between min and max (including equal to min or max) in the ordered set key.
Note: If the command is executed successfully, the number of removed members will be returned.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-4T9UPuU8-1681218054432)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411200151552.png)]
12、zrangebylex
Format: ZRANGEBYLEX key min max [LIMIT offset count]
Function: This command is only applicable when all members in the set have the same score. When all members of a sorted set have the same score, the elements of the sorted set are sorted according to the lexicographical ordering of the members. That is, this command returns the members of the given set whose element values are between min and max. If the members in the sorted set have different scores, the execution result of the command is the same as zrange key.
Note: Legal min and max parameters must contain left parentheses "(" or left brackets "[", where left brackets "(" indicate open intervals, and left brackets "[" indicate closed intervals. min or max The special characters "+" and "-" can also be used to represent positive infinity and negative infinity respectively.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-EPjONsTS-1681218054432)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411205145970.png)]
13、zlexcount
Format: ZLEXCOUNT key min max
Function: This command is only applicable when all members in the set have the same score. This command returns the number of elements in the collection whose element values themselves (not the score value) are between min and max.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-8R7cihDj-1681218054433)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411205406092.png)]
14、zremrangebylex
Format: ZREMRANGEBYLEX key min max
Function: This command is only applicable when all members in the set have the same score. This command removes all elements in the collection whose element values themselves are within the range of min and max.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-IGF4CIPP-1681219975326)(https://typora-1259159092.cos.ap-nanjing.myqcloud.com/typora /image-20230411205517353.png)]
15. Application scenarios
The most typical application scenario of an ordered set is the ranking list, such as the ranking list sorted by the number of playbacks on music and video platforms; the ranking list sorted by user evaluation or sales volume on the e-commerce platform, etc. Use the playback volume as the score, the work id as the member, the user evaluation points or sales volume as the score, and the merchant id as the member. Use zincrby to increase the sorting score, use zrevrange to get the Top few, use zrevrank to query the current ranking, use zscore to query the current sorting score, etc.