In Redis, managing keys efficiently is crucial for optimal performance. Sometimes, you might need to delete keys that match a pattern or have a fuzzy match. Here’s how you can achieve this:

Using Redis CLI Commands

Redis CLI provides several commands to interact with keys. To delete keys that match a pattern, you can use the KEYS command in combination with the DEL command:

1
redis-cli KEYS "pattern*" | xargs redis-cli DEL

Replace "pattern*" with your specific pattern. This command finds all keys matching the pattern using KEYS, then pipes the results to DEL to delete them.

Lua Scripting for Complex Matching

For more complex matching scenarios, Lua scripting in Redis allows for custom logic. Here’s a basic example to delete keys matching a fuzzy pattern:

1
2
3
4
5
local keys = redis.call('KEYS', ARGV[1])
for i=1,#keys do
redis.call('DEL', keys[i])
end
return keys

Save this script, say as delete_fuzzy_keys.lua, and execute it using EVAL command in Redis:

1
redis-cli EVAL "$(cat delete_fuzzy_keys.lua)" 0 "your_pattern*"

Replace "your_pattern*" with your specific pattern.

Automating with Redis Libraries

If you’re using Redis in a programming language, such as Python with redis-py, you can achieve fuzzy key deletion programmatically:

1
2
3
4
5
6
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
keys_to_delete = r.keys("your_pattern*")
for key in keys_to_delete:
r.delete(key)

This Python script uses redis-py to connect to Redis, fetch keys matching "your_pattern*", and delete them using delete() method.

Considerations

  • Performance: Be cautious with KEYS command in production as it scans all keys.
  • Safety: Ensure you’re deleting the correct keys to prevent accidental data loss.

By following these methods, you can effectively manage and delete fuzzy matching keys in Redis according to your needs.