Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Node Redis: Delete Keys By Prefix (Detailed Guide w/ Code Examples)

Use Case(s)

Often times, Redis is used as a cache and it becomes necessary to delete keys based on certain patterns or prefixes. For example, you might want to invalidate all cache entries that have a specific prefix when an update occurs.

Code Examples

The 'redis' module in Node.js doesn't directly support deleting keys by prefix. But you can achieve this by combining the 'KEYS' command and the 'DEL' command.

CODE_BLOCK_PLACEHOLDER_0
In this code, we first obtain all keys with the provided prefix using the 'keys' function and then delete them using the 'del' function.

Best Practices

Common Mistakes

FAQs

Q: Can I use wildcard characters in the key prefix?
A: Yes, you can use wildcard characters like '*' in the prefix to match multiple keys.

Q: What happens when no keys match the prefix?
A: The del command will not delete any keys, and it will return 0.

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