Redis

How to FlushDB in Redis

Redis is a free, open-source key-value data store. It stores data in the system’s memory instead of the disk. This feature allows Redis to be super fast compared to databases such as relational databases. It is mainly used in high-performance and low latency environments.

Using this tutorial, you will learn to delete all the keys in a Redis database and clear the Redis cache.

Basic Usage

The simplest method to clear the Redis cache is to use the Redis CLI utility. Using the command interface, you can delete all keys in a single database or from all databases available in the Redis cluster.

The command takes a syntax as shown below:

redis-cli <db_number> <option>
  • The db_number option allows you to specify the target database you want to clear.
  • Option – used to specify the clear operation.

Let us now use the commands above in an actual Redis database.

Remove Keys from a Specific Database

Redis allows you to remove keys from a specific database by using the flushdb command. This command will remove all the keys in the selected database.

For example:

redis-cli flushdb

If you have Redis hosted on a remote machine, you can specify the host’s address using the -h option as:

redis-cli -h <ip_address> FLUSHDB

It is good to note that using the FLUSHDB command without any arguments will remove all the keys in the selected database. Unless changed, this defaults to database at index 0.

To target a specific database index, you can use the -n option followed by the database index to clear.

The syntax can be expressed as:

redis-cli -n [db_index] FLUSHDB

For example, to clear all keys at the database at index 10, you can do.

redis-cli -n 10 FLUSHDB

Since Redis 4.0 and above, Redis allows you to perform FLUSH operations on a separate thread. This prevents the Flush operations from blocking the server until complete.

To perform FLUSH operation asynchronously, use the ASYNC option as:

redis-cli FLUSHDB ASYNC

Removing All Keys

You can remove all the keys from all the databases in the Redis cluster by using the FLUSHALL command.

The example command is as shown:

redis-cli FLUSHALL

Similarly, you can use the ASYNC option to operate asynchronously without blocking the server.

redis-cli FLUSHALL ASYNC

It is good to note that the FLUSH operations will only delete the keys available during command invocation. Keys that are added during the process will be retained.

Conclusion

In this article, you learned h0w to clear all the keys in a specific database or all databases in the Redis server.

Thank you for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list