Redis operation data common command detailed notes

Time:2021-2-19

Basic operation of redis

Use help to query which commands are available

Help @ string # query string type command
Help @ hash # query hash command
Help @ list # query list command
Help @ set # query set command
Help @ Zset # query Zset command
Help @ cluster # query cluster command
Help @ generic # query General Command

... and other commands, you can use the table key prompt

Example all the key names are bigkang

#Query all keys
keys *    

#Determine whether a key exists
exists <key>
exists bigkang

#Query the type of a key
type <key>
type bigkang

#Delete a key and return the number of affected rows. 1 means true and the deletion is successful
del <key>
del bigkang

#Set the timeout time for the key, in seconds. Return one to indicate true. The setting is successful
expire <key> <seconds>
expire bigkang 30

#Query the key expiration time, and return the positive number of seconds as the timeout time, - 1 means never to expire, - 2 means expired
ttl <key>
ttl bigkang

#View the number of keys in the current database (single database)
dbsize

#Clear current library
Flushdb

#Empty all libraries
Flushall

String operation

Help @ string # query string type command
#Query the key value corresponding to the key
get  <key>
get bigkang

#Set a value, add a key value pair, assign a value of 123 to bigkang, if not, create bigkang
set <key> <value>
set bigkang 123

#Add 456 to bigkang
append <key> <value>
append bigkang 456

#Query the key length, which is also called length
strlen <key>
strlen bigkang

#Set a value. If it does not exist, set a value. If it does exist, the setting fails
setnx <key> <value>
setnx bigkang 123

#Adding 1 to the key value is similar to I + + operation. If it is a string, there will be no return. It must be data, and the return value is the modified value
incr <key>
incr bigkang

#Reducing the key value by 1 is similar to I -- operation. If it is a string, there will be no return. It must be data, and the return value is the modified value
decr <key>
dect bigkang

#Specify the number of keys to add or decrease. Add 100 to the value of bigkang, and then decrease 100. The return value is the modified value
Incrby / decrby < key > < step size > 0
incrby bigkang 100
decrby bigkang 100

#Batch setting of key value pairs
mset <key1> <value1> <key2> <value2>
mset bigkang1 1 bigkang2 2 bigkang3 3

#One or more key value pairs are set at the same time. If they do not exist, they will be set. If one of the conditions is not met, they will all fail
msetnx <key1> <value1> <key2> <value2> 
msetnx bigkang4 1 bigkang5 2 bigkang6 3

#Intercepts the range to obtain the range of values, similar to substring in Java. The initial subscript is 0, and only returns to the end, exceeding the normal return
Getrange < key > < start position > < end position >
getrange bigkang 0 10

#Insert value, insert string from specified position, return string length
Setrange < key > < start position > < value >
setrange bigkang 0 big

#Set the expiration time in seconds while setting the key value
Setex < key > < expiration time > < value >

#Gets the previous value and writes the new value
getset <key> <value>
getset bigkang 123

Hash operation

Help @ hash # query hash type command
#Set the hash value. Hash is similar to map in Java. If the key of hash exists, it returns 0 and if it does not exist, it returns 1. If it is string, an error will be reported. Set the name to bigkang and the age to 21
hset <key> <field> <value>
hset bigkang name bigkang age 21

#Get the value of an attribute from hash
hget <key> <field>
hget bigkang name

#Batch setting hash values
hmset <key> <field1> <value1> <field2> <value2>
hmset bigkang name bigkang1 age 2000

#Get value in batch
hmset <key> <field1> <field2> 
hmget bigkang name age

#Judge whether the field exists, return 0 or 1, corresponding to true and false
hexists <key> <field>
hexists bigkang name

#List all fields of a key
hkeys <key>
hkeys bigkang

#List all values of a key
hvals <key>
hvals bigkang

#Add increment to the value of field in hash table key
hincrby <key> <field> <increment>
hincrby bigkang age 1

#Set the value of the field in the hash table key to value, set it when it does not exist, and set it when it does not exist
hsetnx <key> <field> <value>
hsetnx bigkang name bigkang

String list operation

Help @ list # query list type command
#Insert one or more values from the left / right
lpush/rpush <key> <value1> <value2> <value3>
#Insert left
lpush bigkang 1 2 3
#Insert right
rpush bigkang 4 5 6

#Spit out a value from the left / right
lpop/rpop key
#Spit it out on the left
lpop bigkang
#Spit it out from the right
rpop bigkang

#Spit out a value from the right side of one list and insert it into the left side of another list
rpoplpush <key1> <key2>
rpoplpush bigkang bigkang1

#Get elements (from left to right) by index subscript, index starts from 0
lindex <key> <index>
lindex bigkang 2

#Get the elements (from left to right) according to the range of starting position and ending position, and the index starts from 0
lrange <key> <start> <stop>
lrang bigkang 0 3

#Get list length
llen <key>
llen bigkang

#Find a value according to the key and insert a value before / after it
linsert <key> AFTER/BEFORE <value> <newvalue>
#Insert 0.9 before the value of bigkang is 1
linsert bigkang AFTER 1 0.9
#Insert 1.1 after the value of bigkang is 1
linsert bigkang BEFORE 1 1.1

#According to a key, find the value and delete several values
lrem <key> <n> <value>
#In bigkang, start the query from the left, delete the element 1, and delete two (there may be more than one 1 in the element list)
lrem bigkang 2 1

Operation of string set

Help @ set # query set type command
#If one or more member elements are added to the set key, the member elements that already exist in the set will be ignored. If the insertion is successful, 1 is returned. If the insertion fails, 0 already exists
sadd <key> <value1> <value2> .....    
sadd bigkang 1 2 3
#Gets all the values of the collection
smembers <key>
smembers bigkang

#Returns the number of elements in the collection
scard <key>
scard bigkang

#To determine whether the set < key > contains the < value > value, 1 is returned and 0 is not returned
sismember <key> <value>
sismember bigkang 1

#Delete an element in the collection
srem <key> <value1> <value2> ....    
srem bigkang 1 2 3

#Spit out a value randomly from the set, and the original value will be deleted
spop <key>
spop bigkang

#Randomly take n values from the set. It is not removed from the collection
srandmember <key> <n>
srandmember bigkang 3

#Returns the intersection elements of two sets. If bigkang has 1 and bigkang2 has 1, then 1 is returned. All the same elements will be returned
sinter <key1> <key2>
sinter bigkang bigkang2

#Returns the union elements of two sets. For example, if bigkang is 1 23 and bigkang2 is 3 45, then 1 23 45 is returned
sunion <key1> <key2>
sunion bigkang bigkang2

#Returns the difference set elements of two sets. For example, if bigkang is 1.23 and bigkang2 is 3.45, it returns 1.24.5
sdiff <key1> <key2>
sdiff bigkang bigkang2

Operation of ordered string set (Zset)

help @sorted_ Set # query Zset type command
#Add one or more member elements and their score values to the ordered set key, and Zset will sort according to the score
zadd <key> <score1> <value1> <score2> <value2>...    
zadd bigkang 1 A 2 B 3 C

#Return the elements in the ordered set key whose subscripts are between < start > < stop >, with withscores, so that scores and values can be returned to the result set together. The index starts from 0, and 0 1 will contain 0 and 1
zrange <key> <start> <stop> [WITHSCORES]
#Return three values from 0 to 2 with fraction, and return fraction, from small to large
zrange bigkang 0 2 WITHSCORES
#Do not return score
zrange bigkang 0 2

#Same as above, in reverse order, from big to small
zrevrange bigkang 0 2
#- 1 means to return all
zrevrange bigkang 0 -1

#Returns the value (including) of the score from min to Max in the ordered set key, and the members of the ordered set are arranged in the order of increasing score value (from small to large)
zrangebyscore key min max [withscores][limit offset count]
zrangebyscore bigkang 1 2.5 WITHSCORES

#Same as above, change to arrange from big to small, max min is opposite
zrevrangebyscore key max min [withscores][limit offset count]
zrevrangebyscore bigkang 2.5 1 WITHSCORES

#Add an increment to the score of the element
zincrby <key> <increment> <value>
zincrby bigkang 3 A

#Delete the element with the specified value under the collection
zrem <key> <value>
zrem bigkang A

#Statistics of the set, the number of elements in the fraction interval
zcount <key> <min> <max>
zcount bigkang 1 20

#Returns the ranking of the value in the collection, starting from 0, and returns the index subscript, from small to large
zrank <key> <value>
zrank bigkang B

Bit operation

Setting (bit)

First of all, we need to know what bit is. In fact, all bit operations operate on string types. After setting bit, we can find that its type is actually a string

#Set bit syntax setbit ${key name} ${bit bit} ${the value of bit can only be 0 or 1}
setbit newbit 1 1

Then we get the bit type

#Gets the type of the key
type newbit

#We found that it was back
"string"

​ Then we will find that the data stored is actually a string. What’s the relationship between the string and bit? We know that the underlying string in redis uses SDS. In fact, it stores a char array. In C language, a char is equal to 1 byte, and a byte is equal to 8 bits. We can know that a char can store 8 bits If redis string can store 512MB, let’s see how many bits it can store at most

Maximum storage

​ 512 1024 1024 * 8 = 4294967296 (about 4.3 billion)

​ MB KB Byte BIit

We can store about 4.3 billion bits, and the value of each bit can only be 0 or 1

Our operation setbit newbit 1 1 is to set bit 1, that is, the second bit is set to 1, and bit is an array

The general flow chart is as follows:

Redis operation data common command detailed notes

So we can know that bits 0 – 7 belong to the first byte and 8 – 15 belong to the second byte. Now let’s test it

#Delete the original key
del bitstr
#Add a value of bit 0 to 1
setbit bitstr 0 1
#Since the first char is stored, the length is 1
strlen bitstr

#Then set the bit to 7
setbit bitstr 7 1
#Check the length. Since the first char is stored, the length is still 1
strlen bitstr


#If we set 8 this time, then the length will become 2
setbit bitstr 8 1
#Since the second char is stored, the length will be expanded to 2
strlen bitstr

For example, if we want to get the value of a bit, we use getbit

#Get the data of the first bit
getbit bitstr 0

Statistics (bitcount)

Bitcount can count the data with the value of 1 in our bit array. For example, I want to count the result of the value of bit. (! Note that the statistics are based on a char, that is, a byte = 8bit. Each value represents the corresponding 8 bits

As follows

#Count the number of bit bits of the whole byte array data as 1
bitcount bitstr

Or according to the scope of statistics

#Note that this range is not a statistical bit range, but a statistical bit in char, a char = 8bit
#It means to count the first char, that is, 0 - 8 to 0 - 8, then it is 1 to 1. The first char corresponds to bit 0 - 7
#Indicates statistical char [0] - char [0], bit 0 - 7
bitcount bitstr 0 0
#The return result is 2

#Represents statistical char [0] - char [1], bit 0-15
bitcount bitstr 0 1
#The return result is 3

Function (bitop)

Bit is mainly used to help us to operate on different bits, which is similar to union in set.

Now let’s initialize two bits of data

#Initialize the first bit, set 0 and 4
setbit bit1 0 1
setbit bit1 4 1

#Initialize the second bit and set 3 and 4
setbit bit2 3 1
setbit bit2 4 1

At present, the structure of the two bits is as follows

#Bit 0 1 2 3 4 5 6 7
    bit1     1     0     0     0     1     0     0     0
    bit2   0      0     0     1     1     0     0     0

So we know that since it is binary, there must be operations, such as and, or so on

Redis provides the following

  • ​ AND
  • ​ OR
  • ​ NOT
  • ​ XOR

    The syntax is as follows:

Bitop ${operation} ${new key}.... (other bits)

#The return result is the number of bytes of the new bit. For example, bit 1 - 20 corresponds to char [0] - char [2]. The returned data is the length of the string, that is, strlen

​ AND

#Use and, and Bit1 bit2, and then return the result to newbit
bitop and newbit bit1 bit2

#The operation of and is as follows
#Bit 0 1 2 3 4 5 6 7
    bit1     1     0     0     0     1     0     0     0
                
    bit2   0      0     0     1     1     0     0     0
                
    newbit 0      0     0     0     1     0     0     0
    #And operations, must be 1 and 1 = 1, otherwise all are 0        
  #The return result is only 1 if bit is 4, so it is 1 if bit is used

​ OR

#Use or, or Bit1 bit2, and return the result to newbit
bitop or newbit bit1 bit2

#The operation of or is as follows
#Bit 0 1 2 3 4 5 6 7
    bit1     1     0     0     0     1     0     0     0
                
    bit2   0      0     0     1     1     0     0     0
                
    newbit 1      0     0     1     1     0     0     0
    #Or operation, can be 1 or 0, 0 or 1, as long as there is a 1, then return 1    
  #The return result has bits 0, 3 and 4 as 1, so it is 3 when using bit statistics

​ NOT

#Use not to perform not operation on Bit1, and then return the result to newbit
bitop not newbit bit1

#The operation of not is as follows
#Bit 0 1 2 3 4 5 6 7
    bit1     1     0     0     0     1     0     0     0
                
    newbit 0      1     1     1     0     1     1     1
    #Reverse operation, 0 becomes 1, 1 becomes 0
  #The return result is 6

​ XOR

#Use XOR to XOR Bit1 and bit2, and then return the result to newbit
bitop xor newbit bit1 bit2

#The operation of not is as follows
#Bit 0 1 2 3 4 5 6 7
    bit1     1     0     0     0     1     0     0     0
                
    bit2   0      0     0     1     1     0     0     0
                
    newbit 1      0     0     1     0     0     0     0
    #XOR operation must contain 0 and 1
  #The return result is 6

Bit operation can help us store a large amount of data and status. We can use it in multiple scenarios, such as continuous login of users and statistics of active users.

For example, for the following operation, our key uses the login year month day, the bit uses the user ID, and the status is 1

#We set up user login, there are 4 users login on the 1st
setbit login-2020-12-1 19 1
setbit login-2020-12-1 20 1
setbit login-2020-12-1 21 1
setbit login-2020-12-1 22 1

#Two users logged in on number two
setbit login-2020-12-2 19 1
setbit login-2020-12-2 21 1


#Function operation
#Count the users who have logged in in the last two days
bitop or login-2020-12{1-2} login-2020-12-1 login-2020-12-2

#Statistics of the last two consecutive days of login users
bitop and login-2020-12{1-2} login-2020-12-1 login-2020-12-2