During the development process, you will encounter keys that need to be deleted in batches according to certain rules, such as login_logID (the ID is a variable). Now you need to delete the "login_log*" type Data, but redis itself only has the command keys to query the key value of a class in batches, but there is no command to delete a certain class in batches.
Query first, then delete, use xargs to pass parameters (xargs can convert pipe or standard input (stdin) data into command line parameters), execute the query statement first, and then Delete the queried key value and the original del parameter.
redis-cli KEYS key* (查找条件) | xargs redis-cli del
=>[The number of results returned after execution affects]: (integer) 10[Quantity 10]
Do an experiment, first create three key values of the same type
127.0.0.1:6379> set test1 1
OK
127.0.0.1:6379> set test2 2
OK
127.0.0.1:6379> set test3 3
OK
Query keys
127.0.0.1:6379> keys test*
1) "test3"
2) "test2"
3) " test1"
Exit redis and execute the delete command locally
[root@localhost redis]# redis-cli -a 密码 -n 0(数据库) keys "test*" |xargs redis-cli -a 密码 -n 0(数据库) del Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe. Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe. (integer) 3 (返回行数)
Principle analysis:
This command first executes the keys command through the redis client and fuzzy searches out all key, through the xargs command, use the previously queried key as the input of the subsequent redis del command
It is equivalent to executing redis-cli del test1 test2 test3
Note: redis conditions need to be brought when executing here , -a is to enter the password, -n is to specify the database, if redis is not local or there are other changes, you need to add -h redis server ip, -p port
for example
redis-cli -h 127.0.0.1 (IP address) -p 6379 (port number) -a Password -n 1 (Write the data in the database) KEYS key* (search conditions) | xargs redis-cli ( -h (IP address) -p 6379 (port number) -a password -n 1) del
Supplementary knowledge:
Deletion in redis
1.Redis DEL The command is used to delete existing keys. Non-existing keys will be ignored.
For example:
127.0.0.1:6379> set hello world
OK
127.0.0.1:6379> del hello
(integer) 1
But del can only delete one or more, and cannot delete in batches. It is not applicable when the amount of data to be deleted is too large
2. Clear the data of the entire Redis server: flushall
3. Clear the current All keys in the library: flushdb
The above is the detailed content of How to solve the problem of batch deletion of key values in redis. For more information, please follow other related articles on the PHP Chinese website!