Delete keys matching a pattern in Redis

Created on Mar 19, 2020 by 

  1. copyredis-cli --scan --pattern <pattern> | xargs redis-cli del


description

If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background:

$ redis-cli --scan --pattern users:* | xargs redis-cli unlink

How does the Script Work?

  1. First, we use redis-cli --scan --pattern <pattern> to get a list of keys, one key per line. Since this uses scan, redis server is not blocked.
  2. xargs takes multiple lines and combines them on the same line, so you are essentially running the command del <key1> <key2>...
  3. If you have thousands of keys that match the pattern, xargs will automatically execute redis-cli multiple times.

Source: https://rdbtools.com/blog/redis-delete-keys-matching-pattern-using-scan/

redis-cli


name

redis-cli - Command-line client to redis-server

synopsis

redis-cli [options]

description

Redis is a key-value database. It is similar to memcached but the dataset is not volatile and other datatypes (such as lists and sets) are natively supported.

xargs


name

xargs - build and execute command lines from standard input

synopsis

xargs [-0prtx] [-E eof-str] [-e[eof-str]] [--eof[=eof-str]] [--null]
[-d delimiter] [--delimiter delimiter] [-I replace-str] [-i[replace-
str]] [--replace[=replace-str]] [-l[max-lines]] [-L max-lines]
[--max-lines[=max-lines]] [-n max-args] [--max-args=max-args] [-s max-
chars] [--max-chars=max-chars] [-P max-procs] [--max-procs=max-procs]
[--process-slot-var=name] [--interactive] [--verbose] [--exit]
[--no-run-if-empty] [--arg-file=file] [--show-limits] [--version]
[--help] [command [initial-arguments]]

description

This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial- arguments followed by items read from standard input. Blank lines on the standard input are ignored.