Redis common commands

1, Global command

1. Query key

Keys * query all keys and traverse all key values, complexity O(n)

2. Total number of keys

dbsize queries the total number of keys and directly obtains the total number of keys variable built in redis. The complexity is O(1)

3. Check whether the key exists

exists key returns 1 if it exists and 0 if it does not exist

4. Delete key O(k)

del key [key...] the returned result is the number of keys deleted successfully

5. Key expiration

expire key seconds when the expiration time is exceeded, it will be deleted automatically. The key expires after seconds
Expire key timestamp key expires after the second timestamp
pexpire key milliseconds when the expiration time is exceeded, it will be automatically deleted. The key expires in milliseconds
Pexpireat key milliseconds timestamp key expires after the haos second timestamp
ttl command can view the remaining expiration time of the key hello, unit: seconds (> 0 remaining expiration time; - 1 no expiration time is set; - 2 key does not exist)
pttl is milliseconds> expire k2 100
(integer) 1> ttl k2
(integer) 91> ttl ma
(integer) -1> 

6. Data structure type of key

type key if the hello key is of string type, string will be returned; Returns none if the key does not exist

7. Key rename

rename key newkey
Rename x key newkey will be overwritten only if the newkey does not exist

8. Random return of a key


9. Migration key

(1) move key db (not recommended for reproduction) moves the specified key from the source database to the target database
dump key
Restore key ttl value
Dump+restore can realize the function of data migration between different redis instances. The whole migration process is divided into two steps;
1) On the source redis, the dump command will serialize the key values in RDB format
2) On the target redis, the restore command restores the above serialized values, where ttl parameter represents expiration time and ttl=0 represents no expiration time

source redis> get redis
"world"> dump redis
target redis> get redis
(nil)> restore redis 0 "\x00\x05world\a\x00\xe6\xe3\xe9w\xd8c\xa7\xd8"
OK> get redis

migrate is actually a combination of dump, restore and del commands, which simplifies the operation steps.
Migrate host port key [ key ...] destination-db timeout [replace]
Execute in source redis> migrate 6379 flower 0 1000 replace
(migrate the key flower to the library 0 of the target The timeout is 1000 milliseconds. replace means that if the key flower exists in the target library, it will be overwritten)

10. Traversal key

(1) Full traversal key
keys pattern
For example: keys h, keys [R, l] EDIS, keys, etc

(2) Progressive traversal
Scan can effectively solve the blocking problem of keys command. The amount complexity of scan is O(1)

Database management

1. Switch database
select dbIndex
There are 16 databases by default: 0-15. After entering redis, the default is 0 database. Multiple databases are not recommended

2,flushdb / flushall
It is used to clear the database. flushdb only clears the current database, and flushall clears all databases.

2, Operation for key

1. Set value O(1)

set key value [ex]  [px]  [nx|xx]
ex Set the second expiration time for the key value
px Sets the millisecond expiration time for the key value
nx The key must not exist before it can be set successfully for adding
xx And nx On the contrary, the key must exist before it can be successfully set for update
setnx,setex With the above nx,ex Same function

2. Get value O(1)
nil if get key does not exist

3. Batch setting value O(k)
mset key value [key value ...]
mset a 1 b 2 c 3 d 4

4. Get the value O(k) in batch, where k is the number of keys
mget key [key ...]

5. Count O(1)
incr key
decr key /inceby key increment /decrby key increment
The returned results are divided into three cases:
 if the value is not an integer, an error is returned;
 the value is an integer and returns the result after self increment;
 if the key does not exist, it will increase automatically according to the value of 0, and the return result is 1.

6. Additional value O(1)
append key value can append a value to the end of the string

7. String length O(1)
strlen key
Each Chinese character occupies 3 word bytes

8. Set and return the original value O(1)
getset key value

9. Sets the character o (n) at the specified position, where n is the length of the string

setrange key offeset value> get liming
"class4"> setrange liming 0 m
(integer) 6> get liming

10. Get partial string
getrange key start end start and end are the start and end offsets respectively, starting from 0

3, Hash operation

1. Set value
hset key field value
The hsetnx command is also provided
Eg: hset user:1 name tom

2. Get value

hget key field> hset user:1 name Tom
(integer) 1> hget user:1 name
"Tom"> hget user:1 age

3. Delete field
hdel key field [field...] will delete one or more fields, and the return result is the number of fiels successfully deleted

4. Calculate the number of field s
hlen key

5. Set or get field value in batch
Hmget key field [field ...]
Hmset key field value [field value]

6. Determine whether the field exists
hexists key field

7. Get all field s
hkeys key> hkeys user:1
1) "name"
2) "age"
3) "grand"
4) "city"

8. Get all value s
hvals key> hvals user:1
1) "Tom"
2) "20"
3) "3"
4) "beijing"

9. Get all field s and value s
hgetall key

10. hincrby hincrbyfloat scope is field
hincrby key field
hincrbyfloat key field

11. Calculates the length of the value string
hstrlen key field

4, List operation

The list type originally stores multiple ordered strings, which can be repeated
List of 4 operation types

Add rpush, lpush, linsert
Check lrange, lindex, llen
Delete lpop, rpop, lrem, ltrim
Modify lset
Blocking operation blpop, brpop
1. Add
(1) Insert element from right
rpush key value [value...]

(2) Insert element from left
lpush key value [value...]

(3) Insert an element before or after an element
linsert key before|after pivot value
The linsert command will find the element equal to pivot from the list and insert a new element value before or after it> rpush mylist a b c d e f b a 
(integer) 8> linsert mylist after f g
(integer) 9> lrange mylist 0 -1
1) "a"
2) "b"
3) "c"
4) "d"
5) "e"
6) "f"
7) "g"
8) "b"
9) "a"

2. Search
(1) Gets the list of elements within the specified range
lrange key start end index subscripts are 0 to N-1 from left to right, and - 1 to - N from right to left; The end option contains itself
lrange key 0 -1 can get all elements of the list from left to right
lrange mylist 1 3 get the 2nd to 4th elements in the list

(2) Gets the element of the specified subscript in the list
lindex key index

(3) Get list length
llen key

3. Delete
(1) Pop up elements from the right side of the list
rpop key

(2) Pop up elements from the left side of the list
lpop key

(3) Delete the specified element
lrem key count value
The Lrem command will find the element of = value from the list and delete it. It is divided into three cases according to different count s

 Count>0,From left to right, delete the most count Elements
 Count<0,From right to left, delete the most count Absolute value is an element
 Count=0,Delete all    
list listaaa by a a a a java php b a b> lrem listaaa 5 a
(integer) 5> lrange listaaa 0 -1
1) "java"
2) "php"
3) "b"
4) "b"> lrem listaaa 3 php
(integer) 1> lrange listaaa 0 -1
1) "java"
2) "b"
3) "b"

4. Modification
lset key index newValue modifies the element of the specified index subscript
Eg: lset listaaa 1 python output as java python b

5. Blocking operation
blpop key [key ...] timeout
brpop key [key ...] timeout
blpop and brpop are blocking versions of lpop and rpop. Except for different pop-up methods, the use methods are basically the same. timeout blocking time

(1) The list is empty
Brpop list: Test 3 returns after 3 seconds
brpop list:test 0 has been blocked

(2) List is not empty
brpop mylist 0 returns immediately> brpop mylist 0
1) "mylist"
2) "a"

5, Set operation (non repeatable)

Operations within a collection
1. Add element
sadd key element [element...] returns the number of elements successfully added

2. Delete element
srem key element [element...] returns the number of elements successfully deleted

3. Calculate the number of elements
The time complexity of scar key is O(1), and the internal variables of redis are used directly

4. Determine whether the element is in the collection
Sismember key element returns 1 in the set, otherwise it returns 0

5. Returns a specified number of elements from a collection at random
Srandmember key [count] count can not be written. The default value is 1

6. Pop up elements randomly from the collection
Spop key [count] supports [count] from version 3.2

7. Get all elements
Small members key, lrange and hgetall are relatively heavy commands. Sometimes sscan can be used to complete them

Set between operations
1. Find the intersection of multiple sets sinter key [key...]
2. Find the union of multiple sets
3. Find the difference set sdiff key [key...] of multiple sets. There are some in the first key and none in the second key
4. Save the results of intersection, union and difference sets
sinterstore destination key [ key ...]
sunionstore destination key [ key ...]
sdiffstore destination key [ key ...]
For example: sinterstore user:1_2:inter user:1 user:2 user:1_2:incr is also a collection type

6, ZADD operation (ordered set)

Within the set
1. Add member time complexity O(log(n)), sadd is O(1)
zadd key score member[score member...] the returned result is the number of successfully added elements

2. Calculate the number of members
The time complexity of zcard key scar is O(1), and the internal variables of redis are used directly

3. Calculate a member's score
zsore key member

4. Calculate the ranking of members
zrank key member

5. Delete member
zrem key member [member ...]

6. Increase members' scores
zincrby key increment member

7. Returns the members of the specified ranking range
zrange key start end [withscores] from low to high
zrevrange key start end [withscores] from high to low

8. Returns the members of the specified score range
Zrange key min max [WithCores] [limit offset count] from low score to high score
Zrevrange key max min [WithCores] [limit offset count] scores from high to low

9. Returns the number of members in the specified score range
zcount key min max

10. Deletes ascending elements within the specified ranking
zremrangebyrank key start end

11. Delete members of the specified score range
zremrangebystore key min max

Set between operations
1. Intersection
2. Union
3. Difference set
4. Save the results of intersection, union and difference sets

7, Pub / sub (publish, subscribe)

1,publish channel message           Release news    eg: publish channel:sports 'I want to go eatting'
2,subscribe channel [channel .....]     Subscribe to messages    eg: subscribe channel:sports
3,unsubscribe channel [channel .....]   Unsubscribe
4,psubscribe pattern [pattern ......]    Subscribe by mode
5,unpsubscribe pattern [pattern ......]  Unsubscribe by mode
6,Query subscription
 pubsub channels                    View active channels> pubsub channels
   1) "channel:sports"
   2) "__sentinel__:hello"
  pubsub numsub [channel ......]        View channel subscriptions  pubsub numsub channel:sports
  pubsub numpat                    View mode subscriptions
   The client enters the subscription state after executing the subscription command, and can only receive four commands: subscribe,psubscribe,unsubscribe,punsubscribe;
   The newly opened subscription client cannot receive the previous message of this channel because redis Published messages are not persisted.

8, Transaction

8.1 discard                             , Cancels the execution of all commands within the transaction block
8.2 exec                                , Execute commands within the transaction block
8.3 multi                               , Mark the beginning of a transaction block
8.4 unwatch                             , cancel watch Command for all key Monitoring of
8.5 watch key [key ...]                 , Monitor one or more key,If before the transaction is executed, this kye The transaction is interrupted by other commands

9, Connection

 9.1 auth password                       , Sign in redis Enter password when
 9.2 echo message               , Print a specific message message,Used during testing
 9.3 ping                                , Test the connection with the server, and return if it is normal pong
 9.4 quit                                , Request the server to close the connection with the current client
 9.5 select index                        , Switch to the specified database

10, Server (server)

10.1 bgsave                             , Background asynchronously save data to hard disk
10.2 client setname/client getname      , Set and get name for connection
10.3 client kill ip:port                , The closing address is ip:port Client for
10.4 client list                        , Return all connected client information and statistics in a human readable manner
10.5 config get parameter               , Get run redis Configuration parameters of the server
10.6 config set parameter value         , set up redis Configuration parameters of the server
10.7 config resetstat                   , Reset info Some statistics of the command
10.8 dbsize                             , Return to the current database key Number of
10.9 flushall                           , Empty the whole redis Server data (delete all databases) key)
10.10 flushdb                           , Clear all in the current database key
10.11 info [section]                    , return redis Various information and statistics of the server
10.12 lastsave                          , Return to last redis Time when data was successfully saved to disk
10.13 monitor                           , Real time print out redis Instructions received by the server
10.14 save                              , Will current Redis All data snapshots of the instance(snapshot)with RDB Save to hard disk in the form of file
10.15 slaveof host port                 , Turns the current server into a slave of the specified server
 10.16 slowlog subcommand [argument]     , Redis A logging system used to record query execution time

Keywords: Database Redis Cache

Added by darklight on Fri, 11 Feb 2022 04:31:37 +0200