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:
- 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:
If you have Redis hosted on a remote machine, you can specify the host’s address using the -h option as:
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:
For example, to clear all keys at the database at index 10, you can do.
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:
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:
Similarly, you can use the ASYNC option to operate asynchronously without blocking the server.
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!