others-How to delete redis keys by patterns using redis-cli command?

1. Purpose

In this post, I would demonstrate how to delete redis keys by patterns using redis-cli command.



2. The solution

The solution to delete redis keys by patterns using redis-cli is as follows. Let’s say there is a redis key named reqcount,now if you want to delete all the key starts with reqcount:,the command is as follows:

$ ./src/redis-cli --scan --pattern reqcount:* | xargs ./src/redis-cli del

2.1 What is redis-cli command?

Redis-cli is a :

redis-cli is the Redis command line interface, a simple program that allows to send commands to Redis, and read the replies sent by the server, directly from the terminal. … In interactive mode, redis-cli has basic line editing capabilities to provide a good typing experience.



2.2 What is redis-cli –scan and –pattern ?

SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call.

An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0. The following is an example of SCAN iteration:

redis 127.0.0.1:6379> scan 0
1) "17"
2)  1) "key:12"
    2) "key:8"
    3) "key:4"
    4) "key:14"
    5) "key:16"
    6) "key:17"
    7) "key:15"
    8) "key:10"
    9) "key:3"
   10) "key:7"
   11) "key:1"
redis 127.0.0.1:6379> scan 17
1) "0"
2) 1) "key:5"
   2) "key:18"
   3) "key:0"
   4) "key:2"
   5) "key:19"
   6) "key:13"
   7) "key:6"
   8) "key:9"
   9) "key:11"



What is --pattern ?

Scanning is able to use the underlying pattern matching capability of the SCAN command with the --pattern option.

$ redis-cli --scan --pattern '*-11*'
key-114
key-117
key-118
key-113
key-115
key-112
key-119
key-11
key-111
key-110
key-116



2.3 What is | xargs?

The xargs command is used in a UNIX shell to convert input from standard input into arguments to a command. In other words, through the use of xargs the output of a command is used as the input of another command.

For example:

$ echo 'one two three' | xargs mkdir
$ ls
$ one two three



2.4 What is redis-cli del?

The command redis-cli del is to remove the specified keys. A key is ignored if it does not exist.

redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> DEL key1 key2 key3
(integer) 2
redis> 



3. Summary

In this post, I demonstrated how to use redis-cli and linux pipe commands to del redis keys by patterns. That’s it, thanks for your reading.