How to reset your Redis DB?

How to reset your Redis DB(s)?

How to reset your Redis DB?
Photo by Markus Spiske / Unsplash

Introduction

In this post, I'll briefly share how you can reset your Redis database.

Note that Redis can contain multiple namespaces and databases.

A Redis namespace is a way to group related keys together in Redis. It allows you to partition your Redis data and avoid naming conflicts between different applications or components that use Redis.
A namespace is simply a prefix that you add to all your Redis keys. For example, if you have two applications that use Redis, you might use the prefixes "app1:" and "app2:" to distinguish their keys.
A Redis database is a logical container for Redis data structures. Redis supports multiple databases (by default, 16 databases are available, numbered from 0 to 15), each identified by a unique integer index.
Each database is independent of the others, and you can use different databases to store different types of data or to separate data for different applications or components.

Context

As of this writing, I'm adding some new APIs to the project at work.

We cache certain data for performance reasons.

However, if I want to try with a new set of data, I need to remove the existing one so that the system automatically requests and caches this information.

Here's how I did it.

  • identify which database I need
  • flush all data
  • if I don't know which one exactly, I can flush all

Get the list of databases

redis-cli info keyspace

If you're using Ruby on Rails, get in the console and run:

$redis.info

You should have a list of databases with the number of keys, expiration time and average time to time:

"db0"=>"keys=15,expires=4,avg_ttl=78844008144",

"db1"=>"keys=372,expires=4,avg_ttl=3751410200",

"db3"=>"keys=551,expires=0,avg_ttl=0",

"db4"=>"keys=39,expires=0,avg_ttl=0",

"db5"=>"keys=13,expires=13,avg_ttl=602462089"

Get all keys

redis-cli --scan --pattern '*' | xargs redis-cli del

or

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

If you are using Ruby on Rails, get in the console and run:

$redis.get('*')

redis-cli flushall

redis-cli flushall

This will return OK if successful.

You can also do the same within a Rails console.

$redis.flushall

References

https://redis.io/docs/data-types/

https://redis.io/topics/namespace