瀏覽標籤:

Keys

[Redis]如何找出相關的 Key 一次刪除

一般在 redis-cli > 下進行 Key 的刪除,可以使用

redis-cli> DEL Key0 Key1 Key2 ...

進行遂一指定的 Key 進行刪除,但資料很多的時間要怎麼輸入一堆指定的 Key 呢?如果這些 Key 都有帶前綴 Ex:id_20210411 id_20210412 的話,這樣就只要一個指領就可以進行相關 Keys 的刪除。

redis-cli --raw keys "KeyWord*" | xargs redis-cli del

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[root@localhost ~]$ redis-cli
127.0.0.1:6379> set id_20210409 "test"
OK
127.0.0.1:6379> set id_20210410 "test1"
OK
127.0.0.1:6379> set id_20210411 "test2"
OK
127.0.0.1:6379> set id_20210412 "test3"
OK
127.0.0.1:6379> keys "id_202104*"
1) "id_20210409"
2) "id_20210410"
3) "id_20210411"
4) "id_20210412"
127.0.0.1:6379>
[root@localhost ~]$ redis-cli --raw keys "id_202104*" | xargs redis-cli del
[root@localhost ~]$ redis-cli
127.0.0.1:6379> get id_20210409
(nil)
127.0.0.1:6379> get id_20210410
(nil)
127.0.0.1:6379> keys id_202104*
(empty list or set)
[root@localhost ~]$ redis-cli 127.0.0.1:6379> set id_20210409 "test" OK 127.0.0.1:6379> set id_20210410 "test1" OK 127.0.0.1:6379> set id_20210411 "test2" OK 127.0.0.1:6379> set id_20210412 "test3" OK 127.0.0.1:6379> keys "id_202104*" 1) "id_20210409" 2) "id_20210410" 3) "id_20210411" 4) "id_20210412" 127.0.0.1:6379> [root@localhost ~]$ redis-cli --raw keys "id_202104*" | xargs redis-cli del [root@localhost ~]$ redis-cli 127.0.0.1:6379> get id_20210409 (nil) 127.0.0.1:6379> get id_20210410 (nil) 127.0.0.1:6379> keys id_202104* (empty list or set)
[root@localhost ~]$ redis-cli
127.0.0.1:6379> set id_20210409 "test"
OK
127.0.0.1:6379> set id_20210410 "test1"
OK
127.0.0.1:6379> set id_20210411 "test2"
OK
127.0.0.1:6379> set id_20210412 "test3"
OK
127.0.0.1:6379> keys "id_202104*"
1) "id_20210409"
2) "id_20210410"
3) "id_20210411"
4) "id_20210412"

127.0.0.1:6379>

[root@localhost ~]$ redis-cli --raw keys "id_202104*" | xargs redis-cli del
[root@localhost ~]$ redis-cli
127.0.0.1:6379> get id_20210409
(nil)
127.0.0.1:6379> get id_20210410
(nil)
127.0.0.1:6379> keys id_202104*
(empty list or set)