Deleting Keys by Prefix in Redis using Ruby (Detailed Guide w/ Code Examples)
Use Case(s)
In Redis, keys are used to store data. However, there may be cases where you want to delete all keys that have a common prefix. This is useful when managing grouped data in your Redis instance, for instance, session data prefixed with 'session:', or user data with 'user:'.
Code Examples
Here is an example on how to delete keys by prefix using the Redis
gem in Ruby:
require 'redis' redis = Redis.new # Add some keys redis.set('prefix:1', 'value1') redis.set('prefix:2', 'value2') redis.set('prefix:3', 'value3') redis.set('noprefix:4', 'value4') # Get keys by prefix keys_with_prefix = redis.keys('prefix:*') # Delete keys by prefix deleted_keys_count = redis.del(keys_with_prefix) unless keys_with_prefix.empty? puts deleted_keys_count # will print 3
This script creates a new Redis connection, sets a few key-value pairs, retrieves keys with a specific prefix and then deletes them.
Best Practices
While the above method works, it's not advisable to use it in production if the database contains large amounts of data because it can block the server for a long time, especially the 'KEYS' command. A better way is to use 'SCAN' command which allows iterations through keys in the database without blocking server.
Common Mistakes
One common mistake is forgetting to check if the array of keys is empty before passing it to the del
function. If keys_with_prefix
is empty, the del
function will raise a Redis::CommandError
.
FAQs
1. Can I delete keys by suffix in Redis? While Redis does not support deleting keys by suffix directly, you can do it programmatically by retrieving all keys, filtering by your conditions, and then deleting them.
2. Is there a performance difference between KEYs and SCAN commands? Yes, the SCAN command is generally more efficient than the KEYS command because it allows the server to stay responsive to other incoming commands while iterating through large collections of keys.
Was this content helpful?
Similar Code Examples
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost