Dragonfly

Deleting Redis Keys By Pattern in Ruby (Detailed Guide w/ Code Examples)

Use Case(s)

A common use case for deleting keys by a pattern in Redis using the Ruby programming language includes cases where you need to remove many keys at once that share a common pattern. This could be due to data invalidation, data versioning, or cleanup tasks.

Code Examples

In Ruby, you can use the 'redis' gem to interact with a Redis database. Here are ways to delete keys based on a pattern:

  1. Using SCAN and DEL commands:

```ruby
require 'redis'

redis = Redis.new(host: 'localhost', port: 6379)

cursor = '0'
loop do
cursor, keys = redis.scan(cursor, match: 'your_pattern*')
keys.each { |key| redis.del(key) } unless keys.empty?

break if cursor == '0'
end
```

This code starts a scan operation from the beginning (cursor '0'). For each key that matches the pattern ('your_pattern*'), it deletes the key. The loop ends when the scan has completed and cursor returns to '0'.

  1. Using KEYS and DEL commands (not recommended for production):

```ruby
require 'redis'

redis = Redis.new(host: 'localhost', port: 6379)

keys = redis.keys('your_pattern*')
redis.del(keys) unless keys.empty?
```

This example uses the KEYS command to find all keys matching the pattern, and the DEL command to delete them. However, using KEYS in a production environment is not recommended as it may block the server when processing large keyspaces.

Best Practices

Common Mistakes

FAQs

Q: Can I use wildcards in my pattern?

A: Yes, you can use '' as a wildcard character in your pattern. For example, 'user:' will match all keys that start with 'user:'.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

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