Skip to content

Instantly share code, notes, and snippets.

@wrandowR
Last active May 13, 2022 13:39
Show Gist options
  • Save wrandowR/5c5825f54a5f9287912e749d7a050a1a to your computer and use it in GitHub Desktop.
Save wrandowR/5c5825f54a5f9287912e749d7a050a1a to your computer and use it in GitHub Desktop.
Delete Redis keys with a pattern

Delete Redis keys with a pattern

** Avoid having to create a script to delete a set of Redis keys, do it from your terminal **

Since the Redis client does not have a native function to delete keys given a pattern or expression, it is usually customary to use the KEYS function that allows bringing all the keys that match a pattern and later these keys are traversed and the deletion is executed, but Normally you require a script that is the one that does these operations without being able to do it from the native redis client.

In this snippet we take advantage of one of the advantages of Redis as of version 2.6.0, which is the ability to execute Lua scripts Through the EVAL command, allowing us to delete redis keys from our terminal as if we were using the DEL command but for a pattern that we want.

  • [Redis] (http://redis.io) - Redis is an open source, BSD licensed, advanced key-value cache and store.

** With redis installed **

  1. Open your terminal and enter your redis client, normally running redis-cli is enough.
  2. According to the structure of your base, choose the pattern you want to erase
  3. Replace prefix: * with the pattern you want
  4. Run the script.
  • ** Reference 1: **

EVAL "local keys = redis.call('keys', ARGV[1]) \n for i=1,#keys,5000 do \n redis.call('del', unpack(keys, i, math.min(i+4999, #keys)))\n end \n return keys" 0 prefix:*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment