当前位置:网站首页>Redis learning - 02 common data types, operation commands and expiration time
Redis learning - 02 common data types, operation commands and expiration time
2022-06-26 12:35:00 【Preserved egg is very white】
Redis Common data types and operation commands (CRUD)
Related resources :
- An introduction to Redis data types and abstractions
- Data types
- Command reference
- Redis Chinese translation of official documents ( Some content is not up to date )
This article only lists Redis Some of the commands commonly used in , For a complete list of commands, please read the official documentation .
Redis data type
Redis Not a simple key value store , It's actually a data structure server , Supports different types of values . It means , In traditional key value storage , You can associate a string key with a string value , And in the Redis in , This value is not limited to simple strings , You can also save more complex data structures . Here are Redis A list of all data structures supported in :
type | explain |
---|---|
Strings | character string |
Lists | list , A collection of string elements sorted by insertion order . They are basically linked lists . |
Hashes | Hash / hash , Is a mapping of fields associated with values . Fields and values are strings . This is related to Ruby or Python Hashes are very similar . Be similar to JavaScript Object structure in . Be careful : Cannot nest . |
Sets | aggregate , Unique 、 A collection of unordered string elements , The data in the set is not duplicated . |
Sorted sets | Ordered set / Sort set , And Sets similar , But each string element is associated with a score( fraction ) Associated with the floating-point value of . Elements are always sorted by fraction , Therefore, Sets Different , You can retrieve a series of elements ( for example , You may ask : Before you give it to me 10 Or later 10 individual ). |
Bit arrays( or bitmaps) | You can use special commands to handle string values just as you would handle groups of bits : You can set and clear individual bits , Set all to 1 Bit count , Find the first set or unset bit , And so on . |
HyperLogLogs | This is a probabilistic data structure , Used to estimate the cardinality of a set . |
Streams | Provides an append only collection of similar mapping entries for abstract log data types . |
The following will only introduce the commonly used Strings、Hashes、Sets、Sorted sets type .
Redis The key (keys)
Redis keys It's binary safe , This means that you can use any binary sequence as key, from "foo"
String to JPEG The content of the document . Empty strings are also valid keys .
Some other rules about keys :
- Too long is not good
- Take up memory space
- lookup key When an key The cost of comparison is too high
- If you have to match a larger value , It's best to hash them (hashing, For example, using SHA1)
- Too short is not good
- No readability
- for example , There is no need to
user.1000.followers
Change it tou1000flw
- Try to stick to fixed rules
- for example :
object-type:id
Format , Such asuser.1000
- Dots or dashes are often used in multi word fields , Such as :
comment:1234:reply.to
orcomment:1234:reply-to
- for example :
- The maximum size allowed is 512 MB
data type - character string Strings
The string is Redis The most basic data type in , It is also the basis of other data types .
- It can store any kind of string , Including binary data .
- You can use it to store users' mailboxes 、JSON The object of transformation , Even a picture
- value The maximum data size that can be stored is 512 MB
String types are other common types 4 The basis of data types , The difference between other data types and string types is only the form of organizing characters from a certain point of view .
for example , A list type organizes strings in the form of a list , The collection type is to organize strings in the form of a collection .
add to
Open the command line interactive tool redis-cli
.
# If key Create if it does not exist , If it exists, assign a value
SET key value
# for example : key / Values need not be quoted , The default is string type
# SET foo bar
# OK
# Will be given key The value of the set value, And back to key The old value
GETSET key value
# GETSET foo baz
# bar
# Only in key Set when not present key Value
SETNX key value
# Set one or more... At the same time key-value Yes
MSET key value [key value ...]
# Set one or more... At the same time key-value Yes , If and only if all given key It will be executed successfully only when none exists
MSETNX key value [key value ...]
# If key Already exist , And the value is a string , APPEND The order will specify value Append to the key End of original value , If key non-existent , Then add
APPEND key value
Be careful :
- key / Values need not be quoted , The default is string type
- stay Redis The command is not case sensitive , in other words
SET foo bar
andset foo bar
It's the same , But we agreed to use uppercase to represent a Redis command .
Inquire about
# Get specified key Value
GET key
# return key The child character of the string value in
GETRANGE key start end
# Get all ( One or more ) Given key Value
MGET key [key ...]
# return key The length of the stored string value
STRLEN key
# General Command : Query whether there is a specified in the dictionary key( Returns the number of matches )
EXISTS key [key ...]
# General Command : Inquire about key The type of
TYPE key
modify
# Modify designation key Value
SET key value
# Will be given key The value of the set value, And back to key The old value
GETSET key value
# Additional
APPEND key value
Delete
# General Command : Delete 1 One or more specified key
DEL key [key ...]
Numerical value
The number value is in Redis Save as string in , but Redis Also provided are some methods for parsing strings to Integers The operation of :
# INCR(increment) Will parse the string value to an integer , Incrementing it 1, And set it to the new value
INCR key
# INCRBY You can specify an incrementing number ( Integers )
INCRBY key increment
# DECR(decrement) Decline
DECR key
# Specify the decrement value
DECRBY key decrement
Example :
127.0.0.1:6379> SET count 1
127.0.0.1:6379> GET count
# It's a string
"1"
127.0.0.1:6379> INCR count
# Output new value
(integer) 2
127.0.0.1:6379> INCRBY count 4
(integer) 6
# Redis Cannot parse string to floating point number , Using these commands for non integer strings will result in an error
127.0.0.1:6379> INCRBY count 0.5
(error) ERR value is not an integer or out of range
127.0.0.1:6379> DECR count
(integer) 5
127.0.0.1:6379> DECRBY count 2
(integer) 3
data type - Hash / hash Hashes
Hash Hash ( Also called hash ) A type is a dictionary structure , It stores the mapping of fields and field values ( Key value pair ), But the field value can only be a string , It can't be any other data type . in other words , Hash types cannot be nested with other data types .
Be careful : Except for hash type ,Redis Data type nesting is also not supported for other data types of .
add to
# Add or modify hash table key Key value pairs in
# If no hash exists key Create
# This command will only add key In the field , Or modify the value of an existing field , Does not overwrite the entire key Value
HSET key field value [field value ...]
# There will be more than one field-value Set to hash table key in ( And HSET The effect is the same )
HMSET key field value [field value ...]
# Only in the fields field When there is no , Will set the value of the hash table field
HSETNX key field value
Example :
127.0.0.1:6379> HSET myhash a 1 b 2
# Returns the number of fields added
(integer) 2
127.0.0.1:6379> HSET myhash a 11 c 3
# Only one... Has been added c Field
(integer) 1
# View all fields
127.0.0.1:6379> HKEYS myhash
1) "a"
2) "b"
3) "c"
127.0.0.1:6379> HMSET myhash a 111 d 4
# Return the setting result
OK
127.0.0.1:6379> HKEYS myhash
1) "a"
2) "b"
3) "c"
4) "d"
Inquire about
# Get all hash tables key In the field
HKEYS key
# Get hash table key The number of fields in
HLEN key
# Get all hash tables key Field values in
HVALS key
# Get the value of a single field
HGET key field
# Get the value of all the given fields
HMGET key field [field ...]
# Get all hash tables key Fields and values in
HGETALL key
# Look at the hash table key Whether the field specified in the
HEXISTS key field
Example :
127.0.0.1:6379> HSET myhash a 1 b 2 c 3
(integer) 3
127.0.0.1:6379> HKEYS myhash
1) "a"
2) "b"
3) "c"
127.0.0.1:6379> HLEN myhash
(integer) 3
127.0.0.1:6379> HVALS myhash
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> HGET myhash a
"1"
127.0.0.1:6379> HMGET myhash a b
1) "1"
2) "2"
127.0.0.1:6379> HGETALL myhash
1) "a"
2) "1"
3) "b"
4) "2"
5) "c"
6) "3"
127.0.0.1:6379> HEXISTS myhash c
(integer) 1
modify
# Modify hash table key The value of one or more fields in
HSET key field value [field value ...]
# Methods provided for fields of integer string values
# Be careful : No, HINCR HDECR HDECRBY command
HINCRBY key field increment
Delete
# Delete one or more hash table fields
HDEL key field [field ...]
# General Command : Delete entire hash
DEL key [key ...]
data type - list Lists
List types are used in a way similar to arrays in programming languages , Can store an ordered list of strings , A common operation is to add elements to both ends of the list , Or get a piece of the list .
But it is not quite the same as the concept of array .
Linked list implementation of Redis list
To interpret list data types , It's best to start with a theory , Because information technologists often use terms in incorrect ways “List”. for example ,“Python Lists” Not what the name implies ( Linked list ), It is Array ( The same data type is in Ruby Is actually called Array).
From a very general point of view , A list is just a series of ordered elements :10, 20, 1, 2, 3
It's a list . however , The properties of a list implemented with an array are very different from those of a list implemented with a linked list .
Redis The list is realized through a two-way linked list , The time complexity of adding or obtaining elements to both ends of the list is O(1), The closer you get to both ends, the faster .
It means , Add... At the beginning or end of the list / The operation of getting elements will be completed within a fixed time . For example, to include 10 The rate at which new elements are added to the list headers of elements and to include 1000 The speed of adding elements to the list header of 10000 elements is the same .
shortcoming : The cost of using linked lists is that it is slow to access elements through indexes .
In the list implemented with array , Accessing elements by index is very fast , In the list realized by linked list , Accessing elements by index is not as fast , It will start searching one by one from the first element . In the list , Requires workload proportional to the index of the element being accessed .
advantage : For database systems , Being able to add elements to very long lists in a very fast way is crucial . Another powerful advantage is Redis A list can get elements of a fixed length in a fixed time .
This feature enables list types to quickly accomplish scenarios that relational databases cannot cope with : For example, the news of social networking sites , All we care about is the latest content , Use the list type to store , Even if the total number of new things reaches tens of millions , Get the latest 100 Data is also extremely fast . Also, the time complexity of inserting records at both ends is O(1), The list type is also suitable for logging , It can ensure that the speed of adding new logs will not be affected by the number of existing logs .
When you need to quickly access the middle of a large collection of elements , You can use another data structure (Sorted sets).
add to
# Insert one or more elements into the list header ( Or left )(left push)
# If key non-existent , Create
# Multiple elements are inserted in sequence , That is, the last element added will be the first element of the list
LPUSH key element [element ...]
# The first reference element found in the list (pivot) Insert elements before or after
# When key non-existent , It is regarded as an empty list , Do nothing
# When key There is , But when a value that is not a list type is stored , Returns an error
LINSERT key BEFORE|AFTER pivot element
# If the list key There is , Insert an element into the list header
LPUSHX key element
# Insert one or more elements at the end of the list ( Or right )(right push)
RPUSH key element [element ...]
# If the list key There is , Insert an element at the end of the list
RPUSHX key element
Example :
127.0.0.1:6379> LPUSH mylist 1 2 2 3
# Returns the number of list elements
(integer) 4
# Query the elements within the specified index range `start:0, stop:-1` Means to query all
127.0.0.1:6379> LRANGE mylist 0 -1
# Insert multiple elements into the header in turn , The order is the reverse of the insertion order
1) "3"
2) "2"
3) "2"
4) "1"
127.0.0.1:6379> LINSERT mylist BEFORE 2 a
# Returns the number of list elements
(integer) 5
127.0.0.1:6379> LRANGE mylist 0 -1
# Insert only once before the first queried reference element
1) "3"
2) "a"
3) "2"
4) "2"
5) "1"
127.0.0.1:6379> LPUSHX mylist2 x
# There is no the key Do not insert
(integer) 0
127.0.0.1:6379> LRANGE mylist2 0 -1
(empty array)
127.0.0.1:6379> RPUSH mylist 7 8 9
(integer) 8
127.0.0.1:6379> LRANGE mylist 0 -1
1) "3"
2) "a"
3) "2"
4) "2"
5) "1"
6) "7"
7) "8"
8) "9"
Inquire about
# Get the elements in the list by index
LINDEX key index
# Get list length
LLEN key
# Get the elements within the specified index range of the list
# stop The element in which it is located will also be returned
# A positive number means from front to back , A negative number means from back to front , for example stop by -1 Indicates the query to the end
LRANGE key start stop
modify
# Set the value of the list element through the index
# If the index exceeds the range of the list, an error will be reported
LSET key index value
Delete
# From the head ( left ) Delete and get the elements of the list , Delete one by default
# count Specify the number of elements to delete , The default is minimum 1
LPOP key [count]
# From the tail ( On the right side ) Delete and get the elements of the list , Delete one by default
RPOP key [count]
# Delete the specified number of list elements equal to the specified value
# count>0: Delete... From beginning to end count The number of is equal to element The elements of
# count<0: Delete... From end to end count The number of is equal to element The elements of
# count=0: Delete equals element All elements of
LREM key count element
# Trim list , Make the list keep only the elements of the specified index range , Delete elements outside the scope
LTRIM key start stop
# Delete and get source Last element of list , Add this element to destination The head of the list , And return the element
RPOPLPUSH source destination
# Other blocking versions of the command -------------------------------
# LPOP Blocking version of
# Check the given list in order , If at least one of these lists is not an empty list , be pop Its first element and returns
# When one or more of the given lists does not have a list to pop The elements of ( An empty list ) when , Will block the connection , Until another client executes... On one of the lists LPUSH or RPUSH Add element operation .
# timeout Specifies the maximum number of seconds to block , If set to 0, Then it means infinite blocking
# When BLPOP Causes the client to block and specifies a non 0 Of timeout when , The client will wait for two situations :
# 1. Reach the specified timeout time , Unblock
# 2. Within the timeout period , Execute... On at least one list PUSH operation , The client will execute POP Operate and unblock
# If
BLPOP key [key ...] timeout
# RPOP Blocking version of
BRPOP key [key ...] timeout
# RPOPLPUSH Blocking version of
# When source Block connection when list is empty
BPOPLPUSH source destination timeout
data type - aggregate Sets
The set type is similar to the set concept in Mathematics , The elements in the collection are unique 、 A disorderly , Simply understand that a set is a list of strings that have no order and are not repeated .
Collection types and list types have similarities , The main difference between them is :
- The list is ordered , Sets are unordered (Sorted sets Is ordered )
- The list data can be repeated , There is no duplicate data in the collection
A common operation of a collection type is to add or remove elements... To the collection 、 Determine whether an element exists, etc . Because the collection type is in Redis The internal is implemented by using a hash table with an empty value , So the time complexity of these operations is O(1).
The most convenient thing is that multiple sets can also be merged 、 Intersection and difference aggregation operations .
add to
# Add one or more members to the collection
# If key non-existent , Create ; If key If the stored is a collection type, an error is reported
# If member There is , It ignores
SADD key member [member ...]
Example :
127.0.0.1:6379> SADD myset 1 2 3 a b c
(integer) 6
# View the elements under the collection
127.0.0.1:6379> SMEMBERS myset
# Sets are unordered , The order in which the results are added and inserted may be different
1) "2"
2) "a"
3) "3"
4) "c"
5) "1"
6) "b"
Inquire about
# Returns all members of the collection
# The effect is equivalent to SINTER key
SMEMBERS key
# Gets the cardinality of the collection (cardinality), Number of members
SCARD key
# Judge member Is the element a collection key Members of
SISMEMBER key member
# Randomly returns one of the sets ( Default ) Or more members
# count>0: Returns an array containing different elements , The length of the array is taken as count and base (SCARD) Lower value
# count<0: Returns an array that is allowed to contain the same elements , The array length is count The absolute value of
# count=0: Return an empty array
SRANDMEMBER key [count]
Delete
# Remove one or more members of the collection
SREM key member [member ...]
# Randomly remove and return one or more members of the collection
SPOP key [count]
# take member from source The assembly moves to destination aggregate
SMOVE source destination member
Aggregation operations between sets
There can also be... Between multiple sets Combine 、 intersection and Difference set Aggregate operations .
# Returns the set resulting from the difference between the first set and the other sets
SDIFF key [key ...]
# Returns the set generated by the intersection of all given sets
# Specify only the first key(SINTER KEY), Equate to SMEMBERS key
SINTER key [key ...]
# Returns the set resulting from the union of all given sets
SUNION key [key ...]
# Returns the difference set of a given set and stores it in destination in
SDIFFSTORE destination key [key ...]
# Returns the intersection of a given set and stores it in destination in
SINTERSTORE destination key [key ...]
# The union of all given sets is stored in destination Collection
SUNIONSTORE destination key [key ...]
Use scenarios
- Track some unique data
- For example, the only person who visits the website IP Address information , Record users every time you visit the website IP Address ,SET Automatically guarantee the uniqueness of data
- make the best of SET Easy and efficient aggregation operation , It is used to maintain the relationship between data objects
- Such as all purchases A Customers of goods ID Store to the specified SET in , All purchases B Customers of goods ID Store to the specified SET in , If we want to find out which customer has purchased both products at the same time , We just need to use the intersection operation to easily find out
data type - Ordered set Sorted sets
An ordered set is a set similar to Set and Hash Mixed data types between .
- Like a collection , An ordered set consists of a unique 、 Non repeating string elements
- The elements in the collection are not sorted , But each element in an ordered set is associated with a double Type of score( It's called a score )( This is why this type is also similar to hashing , Because each element is mapped to a value )
- The elements in an ordered set are sorted according to the following rules :
- If A and B Different scores , Those with low scores are in the top
- If A and B The scores are the same , In dictionary order , for example a stay b front
vs Lists type
Ordered sets are similar in some ways to list types :
- The same thing :
- Both are orderly
- Both can get a range of elements
- Difference :
- The list type is realized through linked list , Getting data close to both ends is extremely fast , And when the elements increase , Access to intermediate data will be slower , So it is more suitable to implement such as “ Nothing new ” or “ journal ” In this way, applications that rarely access intermediate elements
- An ordered set is implemented using a data structure that contains a hash table , So even if you read the data in the middle , It's also very fast
- A list cannot simply adjust the position of an element , But ordered sets can ( When you insert elements or change the scores of elements, you are already in order )
- Ordered collections consume more memory than lists
Application scenarios
Typical application scenarios for ordered collections :
(1) Ranking List
For example, the score ranking of a large online game , Whenever a player's score changes , It can be executed ZADD
Command to update player's score , After that, we will pass ZRANGE
Command to get points TOPTEN User information for . Of course, we can also use ZRANK
Command to pass username To get player ranking information . Finally, we will combine ZRANGE
and ZRANK
Command to quickly get information of other users who are close to a player's points .
(2) Microblog hot search
Suppose we now want to get popular posts or search , For example, we often use microblog hot search .
First , We need a measure , Quantitatively measure the popularity of hot search . Suppose we have a field called reply quantity , The higher the number of replies, the more popular .
If we use a relational database to get it , use SQL Statement implementation is simple :
SELECT * FROM message ORDER BY backsum LIMIT 10
But when there's a lot of data , Efficiency is very low , At the same time, if the index is established, it will consume a lot of resources , Increase the load at the same time .
Use Redis When , We don't need to store extra information , Just store the posts id And the number of replies .
add to
# Create an ordered collection 、 Add one or more members... To an ordered collection 、 Update scores of existing members
# `score` It's a double floating point number , `+inf`、`-inf` It's also a valid value ( Means negative infinity and positive infinity )
ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...]
Options
ZADD Support a list of options , stay key After and first score It was specified before , Options include :
XX
: Update only existing elements , Do not add new elementsNX
: Just add new elements , Do not update existing elementsLT
: Update existing elements only if the new score is less than the current score , This flag does not prevent adding new elementsGT
: Update existing elements only if the new score is greater than the current score , This flag does not prevent adding new elementsCH
:ZADD By default, the number of newly added elements will be returned . UseCH
Options , Will return the changed number of elements instead (CH yes changed Abbreviation ). The changed element refers to the new element added and the existing element updating the score , Therefore, elements with the same scores as those in the past specified on the command line are not counted .INCR
:(increment) Specify this option ,ZADD The behavior of is similar to ZINCRBY, The increment of the score is added to the current score of the element , Only one... Can be specified in this mode score-member Yes . Specify this option ,ZADD The return value of is the latest score of the element .
Be careful :GT
,LT
and NX
Options are mutually exclusive .
Sort
Ordered sets are sorted in ascending fractional order , The same element exists only once , Duplicate elements are not allowed . It can be done by ZSCORE Command to retrieve the current score of an element , It can also be used to verify whether an element exists .
When multiple elements have the same score , In dictionary order .
Inquire about
Interval query
# Perform different types of range queries , Returns the members in the specified interval of an ordered set
ZRANGE key min max [BYSCORE|BYLEX] [REV] [LIMIT offset count] [WITHSCORES]
Options :
- Query type :
- Default : Assign ranking (rank)Index Index range ,
min
andmax
From 0 Index started , If it's negative , Represents the offset from the end , for example-1
Is the last element of an ordered set ,-2
It's the second to last . BYSCORE
: Specify score (Score) Section- Returns a score equal to or between in an ordered set
min
andmax
Element range between - Scores can be specified
-inf
and+inf
- By default ,
min
andmax
What is specified is a closed interval[min, max]
, That is, the specified range contains equal tomin
ormax
, You can add a character before the fraction(
Close the range , That is, the range does not include equal tomin
ormax
, for example(1 5
Express(1, 5]
,(1 (5
Express(1, 5)
. - Using this option is similar to ZRANGEBYSCORE command .
- Returns a score equal to or between in an ordered set
BYLEX
: Specify a dictionary (Lexicographical) Sectionmin
andmax
Must be based on(
or[
Starting string , To specify whether the range is open or closed .min
andmax
It can also be-
and+
Special values , Means negative infinity and positive infinity respectively .- Be careful : Dictionary ordering depends on all elements with the same score , When elements have different scores , Sorting takes precedence over sorting by score .
- Using this option is similar to ZRANGEBYLEX command .
- Default : Assign ranking (rank)Index Index range ,
REV
Option specifies whether to reverse sort and return- This option only supports the default index query type
LIMIT offset count
Used to get child returns from matching elements , similar SQL MediumSELECT LIMIT offset, count
.- From the matching results
offset
Index position start ( The first is 0), returncount
Number of matching elements . - If
count
It's a negative number , Return fromoffset
All elements to the end . - Use this option
offset
andcount
All must be filled. . - This option only supports
BYSCORE
andBYLEX
Query type
- From the matching results
WITHSCORES
: Return the scores together , The returned list containsmember1 score1 member2 score2 ...
- This option only supports
BYSCORE
And the default index query type
- This option only supports
Example :
127.0.0.1:6379> ZADD myzsort 1 a 2 b 2 c 1 d 3 e
(integer) 5
# Ranking index range + Reverse sorting
127.0.0.1:6379> ZRANGE myzsort 1 3 REV
1) "c"
2) "b"
3) "d"
# Score range
127.0.0.1:6379> ZRANGE myzsort 1 2 BYSCORE
1) "a"
2) "d"
3) "b"
4) "c"
# Specify the sub range
127.0.0.1:6379> ZRANGE myzsort 1 2 BYSCORE LIMIT 1 2
1) "d"
2) "b"
# Back to the score
127.0.0.1:6379> ZRANGE myzsort 1 2 BYSCORE LIMIT 1 2 WITHSCORES
1) "d"
2) "1"
3) "b"
4) "2"
# Dictionary interval , Priority score sorting
127.0.0.1:6379> ZRANGE myzsort (a [e BYLEX
1) "d"
2) "b"
3) "c"
4) "e"
This method can replace the following command :ZREVRANG、ZRANGEBYSCORE、ZREVRANGEBYSCORE、ZRANGEBYLEX and ZREVRANGEBYLEX
# Return the elements in the specified interval of the ordered set through the index interval , Rank scores from high to low
ZREVRANGE key start stop [WITHSCORES]
# Returns the elements within the specified fraction range in an ordered set , Sort scores from high to low
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
# Returns the elements within the specified fraction range in an ordered set , Rank scores from high to low
ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
# Returns the elements of a specified dictionary interval in an ordered set , Score from low to high , The elements of the same division are sorted from low to high in dictionary order
ZRANGEBYLEX key min max [LIMIT offset count]
# Returns the elements of a specified dictionary interval in an ordered set , Scores go from high to low , The elements of the same division are sorted from high to low in dictionary order
ZREMRANGEBYLEX key min max
Other inquiries
Next time, look at it from here
# Returns the rank of a specified member in an ordered set , The members of an ordered set are valued by fractions ( From low to high ) Sort , ranking ( Or index ) from 0 Start
ZRANK key member
# Get the ranking of members whose scores are arranged from height to bottom
ZREVRANK key member
# Get the number of members of the ordered set
ZCARD key
# Back to the ordered set , The score of a member
ZSCORE key member
# Calculates the number of members of a specified interval fraction in an ordered set
# The default is closed range , You can add... Before the score `(` Specify the open interval , You can also specify `-inf` and `+inf`
ZCOUNT key min max
modify
# Add one or more members... To an ordered collection , Or update scores of existing members
ZADD key [XX] [GT|LT] [CH] [INCR] score member [score member ...]
# Add the increment... To the score of the specified member in the ordered set increment
ZINCRBY key increment member
Delete
# Remove one or more members of an ordered collection
ZREM key member [member ...]
# Remove all members of a given rank range from an ordered set
ZREMRANGEBYRANK key start stop
# Remove all members of a given fraction interval from an ordered set
ZREMRANGEBYSCORE key min max
# Remove all members of a given lexicographically ordered interval from an ordered set
ZREMRANGEBYLEX key min max
Aggregation operations between ordered sets
# Calculates the intersection of a given ordered set or sets , And store the result set in a new ordered set destination in
ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
# Computes the union of a given ordered set or sets , And store the result set in a new ordered set destination in
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
- destination: The goal of storing results key, If the goal already exists , It will cover
- numkeys: In the specified calculation keys Before , You must provide key The number of
- If numkeys And keys The number is not the same , Syntax error is reported .
- WEIGHTS: The weight , Specify the multiplication factor for each ordered set , This means that before passing to the aggregate function , The score of each element in each set is multiplied by this factor . By default , The weight of 1.
- If you use this parameter , You must specify a multiplication factor for each set , If the specified number of factors is the same as keys The quantity is not consistent , Syntax error is reported .
- AGGREGATE: Aggregation options , Specifies how to calculate the score of the union element when aggregating .
- SUM: The default value is , Sum of fractions of the same elements
- MIN: The smallest fraction of the same element
- MAX: The maximum fraction of the same element
General Command
# Returns all that match the pattern key
KEYS pattern
# Back to all key
KEYS *
# Return to all with my At the beginning key
KEYS my*
# obtain key The type of
TYPE key
# Query a key Whether there is , Return the existing quantity
EXISTS key [key ...]
# take key Renamed as newkey
RENAME key newkey
# Delete the specified key
DEL key [key ...]
# Random return from the current database ( Don't delete ) One key
RANDOMKEY
# Clear all contents of the current database
FLUSHDB [ASYNC|SYNC]
# Empty all database contents
FLUSHALL [ASYNC|SYNC]
# Will be the current database of key Move to a given database db among
# If... Exists in the target database key, Or there is no... In the current database key, Do nothing
# If the move is successful, return 1, Move failure returns 0
MOVE key db
Redis Expiration time
In the actual development, we often encounter some time effective data , For example, limited time discount 、 Cache or verification code, etc , After a certain time, you need to delete these data . In a relational database, you usually need an additional field to record the expiration time , Then regularly detect and delete expired data . And in the Redis You can set the expiration time of a key , When it's time Redis It will be automatically deleted .
Set the expiration time of the key
# For a given key Set the lifetime ( second )
EXPIRE key seconds [NX|XX|GT|LT]
# For a given key Setup time ( millisecond )
PEXPIRE key milliseconds [NX|XX|GT|LT]
# For a given key Set the lifetime (UNIX Time stamp , In seconds )
EXPIREAT key timestamp [NX|XX|GT|LT]
# For a given key Set the lifetime (UNIX Time stamp , In Milliseconds )
PEXPIREAT key milliseconds-timestamp [NX|XX|GT|LT]
Options :
- NX: Only when the key No expiration time is set
- XX: Only when the key Only when the current expiration time is set
- GT: Set only when the new expiration time is greater than the current expiration time
- LT: Set only if the new expiration time is less than the current expiration time
persistent key ( Expiration time is not set ) The current expiration time of is considered infinite TTL.GT、LT and NX They are mutually exclusive. .
The above four commands are given key Set the lifetime , When key expires , It will be deleted automatically .
by key Set expiration time , It is also stored in a dictionary in a key value structure , The key is a pointer to this key The pointer to , Value is a long integer UNIX Time stamp .
Be careful : Call... With a non positive number EXPIRE/PEXPIRE Or use the past time to call EXPIREAT/PEXPIREAT Will lead to key Be deleted , Not expired ( therefore , The triggered event will be del
, instead of expired
).
Get key expiration time
# In seconds , Return to a given key The remaining lifetime of (TTL, time to live).
TTL key
# Be similar to TTL, The unit is millisecond
PTTL key
# In seconds , Return to a given key Expiration timestamp of
EXPIRETIME key
# similar EXPIRETIME, The unit is millisecond
PEXPIRETIME key
If the command to get the expiration time returns a negative number , Indicates an error :
-1
:key There is , But there is no expiration date-2
:key non-existent
The expiration time of the clear key
stay Redis In terms of , Set the expiration time of key go by the name of volatile ( Volatile ), There is no associated expiration time key go by the name of persistent ( lasting ).
There are two ways to clear the expiration time :
1、 Use PERSIST Order clear key The expiration time of , take key from Volatile Turn into lasting .
PERSIST key
2、 Delete or overwrite key Content command
Include DEL、SET、GETSET And all *STORE The command will clear the expiration time .
All conceptual changes are stored in key Value on , Instead of replacing its operation with a new value , The expiration time will remain unchanged . for example INCR Increasing key Value 、 Use LPUSH Push the new value to the list , Or use HSET Change the field value of the hash , These operations will keep the expiration time unchanged .
If you use RENAME Rename a key, The associated expiration time will be transferred to the new key name .
If Key-A Rename to an existing Key-B, It belongs to the operation of overwriting content . Whatever it is Key-B Is there an expiration date , It will inherit Key-A The expiration time of .
边栏推荐
- 大智慧哪个开户更安全,更好点
- The laravel dingo API returns a custom error message
- Which is safer and better for great wisdom to open an account
- Scala-day02- variables and data types
- The loss of female scientists
- File decryption in webgame development
- [probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
- VMware虚拟机 桥接模式 无法上网 校园网「建议收藏」
- Research on the current situation of China's modified engineering plastics market and demand forecast analysis report 2022-2028
- Analysis report on dynamic research and investment planning suggestions of China's laser medical market in 2022
猜你喜欢
Vscode solves the problem of Chinese garbled code
PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
[solved] data duplication or data loss after laravel paginate() paging
Installing MySQL under Linux (RPM package installation)
栈,后入先出
关于NaN的一些总结
Spark-day02-core programming-rdd
Scala-day06- pattern matching - Generic
Spark-day03-core programming RDD operator
This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
随机推荐
imagecopymerge
[solved] data duplication or data loss after laravel paginate() paging
The laravel dingo API returns a custom error message
PolarisMesh系列文章——概念系列(一)
Jsonarray and jsonobject of fastjson [easy to understand]
Vscode solves the problem of Chinese garbled code
Omnichannel membership - tmall membership 1: opening tutorial
7-1 n皇后问题
PHP generate order number
Hello! Forward proxy!
Scala-day01- companion objects and HelloWorld
Analysis report on China's photovoltaic inverter market prospect forecast and investment strategy recommendations in 2022
Operation analysis and investment prospect research report of China's organic chemical raw material manufacturing industry 2022-2028
"Pinduoduo and short video speed version", how can I roast!
Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source
Investment planning and forecast report on the future direction of China's smart agriculture during the 14th five year plan (2022)
简易数字电路交通灯设计
2016年四川省TI杯电子设计竞赛B题
Seven major trends deeply affecting the U.S. consumer goods industry in 2022
TSMC Samsung will mass produce 3nm chips in 2022: will the iPhone be the first?