876

I want to delete all keys. I want everything wiped out and give me a blank database.

Is there a way to do this in Redis client?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

25 Answers25

1417

With redis-cli:

  • FLUSHDB – Deletes all keys from the connection's current database.
  • FLUSHALL – Deletes all keys from all databases on current host.

For example, in your shell:

redis-cli flushall
GreenROBO
  • 4,725
  • 4
  • 23
  • 43
Javier
  • 60,510
  • 8
  • 78
  • 126
  • 1
    When i try the above i get the following error `(error) LOADING Redis is loading the dataset in memory`. Can you specify why? – Ram Patra Oct 27 '14 at 06:57
  • 8
    @Ramswaroop - you restarted Redis and it is currently loading data from persistent storage. While this process (loading) is active, you can't manipulate the DB. Either wait for it to finish, or configure Redis w/o persistence and restart it (it will start empty so you won't need to do FLUSHALL once it is up). – Itamar Haber Oct 27 '14 at 10:57
  • that my Friend DID the trick, forgot about redis, clearing out the cache and now schema:update works. – Hertzel Armengol Nov 05 '15 at 16:45
  • 1
    @Neo if you don't have a redis client library in C#, you can simply run that command, like so: `(new Process { StartInfo = new ProcessStartInfo { FileName = "redis-cli", Arguments = "flushall", CreateNoWindow = true }}).start();` – Christian Jul 29 '16 at 08:17
  • 2
    Use the `-h` flag to specify a redis server location – Adam Fowler Apr 12 '17 at 18:20
  • And the `-p` flag to specify the port if it is not the standard 6379 – Leo Apr 26 '18 at 17:05
  • I am running redis as cluster mode (`redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1`) and I am using redis-clustr node package. flushall is not deleting all keys. But let = keys = client.keys("*"); client.del(keys) is working fine. – Bopsi May 06 '20 at 07:07
  • This flushes data, yes, but, when restarting redis, the data re-appears. Seems like its loaded from disk on every start. Removing the file "dump.rdb" clears the cached data. – Ted Jun 17 '21 at 11:49
222

Heads up that FLUSHALL may be overkill. FLUSHDB is the one to flush a database only. FLUSHALL will wipe out the entire server. As in every database on the server. Since the question was about flushing a database I think this is an important enough distinction to merit a separate answer.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Real Bill
  • 14,884
  • 8
  • 37
  • 39
  • 4
    +1 from me, i thought this was the better answer actually. Granted, the OP's Question says "wipe everything out" but that is followed by "give me a blank database"--regardless of what he actually meant, i think the distinction you made is useful, to say the least. – doug Aug 01 '11 at 02:47
31

Answers so far are absolutely correct; they delete all keys.

However, if you also want to delete all Lua scripts from the Redis instance, you should follow it by:

SCRIPT FLUSH

The OP asks two questions; this completes the second question (everything wiped).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tw Bert
  • 3,659
  • 20
  • 28
  • If you are running the server yourself, the quickest way to wipe everything is to kill the server and restart it (found this out accidentally) – acutesoftware Aug 31 '14 at 02:22
24

FLUSHALL Remove all keys from all databases

FLUSHDB Remove all keys from the current database

SCRIPT FLUSH Remove all the scripts from the script cache.

Jain Rach
  • 4,069
  • 1
  • 16
  • 25
18

you can use flushall in your terminal

redis-cli> flushall
mar1
  • 193
  • 1
  • 3
17

If you're using the redis-rb gem then you can simply call:

your_redis_client.flushdb
Gerard
  • 4,818
  • 5
  • 51
  • 80
12

This method worked for me - delete everything of current connected Database on your Jedis cluster.

public static void resetRedis() {
    jedisCluster = RedisManager.getJedis(); // your JedisCluster instance

    for (JedisPool pool : jedisCluster.getClusterNodes().values()) {

        try (Jedis jedis = pool.getResource()) {
            jedis.flushAll();
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
        }
    }

}
Kaidul
  • 15,409
  • 15
  • 81
  • 150
8

One more option from my side:

In our production and pre-production databases there are thousands of keys. Time to time we need to delete some keys (by some mask), modify by some criteria etc. Of course, there is no way to do it manually from CLI, especially having sharding (512 logical dbs in each physical).

For this purpose I write java client tool that does all this work. In case of keys deletion the utility can be very simple, only one class there:

public class DataCleaner {

    public static void main(String args[]) {
        String keyPattern = args[0];
        String host = args[1];
        int port = Integer.valueOf(args[2]);
        int dbIndex = Integer.valueOf(args[3]);

        Jedis jedis = new Jedis(host, port);

        int deletedKeysNumber = 0;
        if(dbIndex >= 0){
            deletedKeysNumber += deleteDataFromDB(jedis, keyPattern, dbIndex);
        } else {
            int dbSize = Integer.valueOf(jedis.configGet("databases").get(1));
            for(int i = 0; i < dbSize; i++){
                deletedKeysNumber += deleteDataFromDB(jedis, keyPattern, i);
            }
        }

        if(deletedKeysNumber == 0) {
            System.out.println("There is no keys with key pattern: " + keyPattern + " was found in database with host: " + host);
        }
    }

    private static int deleteDataFromDB(Jedis jedis, String keyPattern, int dbIndex) {
        jedis.select(dbIndex);
        Set<String> keys = jedis.keys(keyPattern);
        for(String key : keys){
            jedis.del(key);
            System.out.println("The key: " + key + " has been deleted from database index: " + dbIndex);
        }

        return keys.size();
    }

}

Writing such kind of tools I find very easy and spend no more then 5-10 min.

miken32
  • 42,008
  • 16
  • 111
  • 154
Denys
  • 1,308
  • 12
  • 13
7

Use FLUSHALL ASYNC if using (Redis 4.0.0 or greater) else FLUSHALL.

https://redis.io/commands/flushall

Note: Everything before executing FLUSHALL ASYNC will be evicted. The changes made during executing FLUSHALL ASYNC will remain unaffected.

Masood Khaari
  • 2,911
  • 2
  • 23
  • 40
arnabmitra
  • 903
  • 9
  • 19
7

Open redis-cli and type:

FLUSHALL
hellow
  • 12,430
  • 7
  • 56
  • 79
behzad babaei
  • 1,111
  • 10
  • 11
  • 1
    Although your post might answer the question, it lacks some documentation. Please edit your answer and provide those. – hellow Aug 17 '18 at 09:29
6

FLUSHALL Deletes all the Keys of All exisiting databases . FOr Redis version > 4.0 , FLUSHALL ASYNC is supported which runs in a background thread wjthout blocking the server https://redis.io/commands/flushall

FLUSHDB - Deletes all the keys in the selected Database . https://redis.io/commands/flushdb

The time complexity to perform the operations will be O(N) where N being the number of keys in the database.

The Response from the redis will be a simple string "OK"

athavan kanapuli
  • 462
  • 1
  • 6
  • 19
5

You can use FLUSHALL which will delete all keys from your every database. Where as FLUSHDB will delete all keys from our current database.

5
  1. Stop Redis instance.
  2. Delete RDB file.
  3. Start Redis instance.
Denys
  • 1,308
  • 12
  • 13
  • In my experience, if you have persistence, you should indeed follow this procedure + also delete any .aof file + issue redis-cli flushall, to really remove everything. – ywarnier Jun 06 '20 at 07:06
5

redis-cli -h <host> -p <port> flushall

It will remove all data from client connected(with host and port)

gobi
  • 511
  • 5
  • 13
4

After you start the Redis-server using:service redis-server start --port 8000 or redis-server.

Use redis-cli -p 8000 to connect to the server as a client in a different terminal.

You can use either

  1. FLUSHDB - Delete all the keys of the currently selected DB. This command never fails. The time-complexity for this operation is O(N), N being the number of keys in the database.
  2. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one. This command never fails. The time-complexity for this operation is O(N), N being the number of keys in all existing databases.

Check the documentation for ASYNC option for both.

If you are using Redis through its python interface, use these two functions for the same functionality:

def flushall(self):
    "Delete all keys in all databases on the current host"
    return self.execute_command('FLUSHALL')

and

def flushdb(self):
    "Delete all keys in the current database"
    return self.execute_command('FLUSHDB')
Archit Singh
  • 109
  • 9
3

i think sometimes stop the redis-server and delete rdb,aof files。 make sure there’s no data can be reloading. then start the redis-server,now it's new and empty.

tcrabsheen
  • 106
  • 2
2

You can use FLUSHDB

e.g

List databases:

127.0.0.1:6379> info keyspace
# Keyspace

List keys

127.0.0.1:6379> keys *
(empty list or set)

Add one value to a key

127.0.0.1:6379> lpush key1 1
(integer) 1
127.0.0.1:6379> keys *
1) "key1"
127.0.0.1:6379> info keyspace
# Keyspace
db0:keys=1,expires=0,avg_ttl=0

Create other key with two values

127.0.0.1:6379> lpush key2 1
(integer) 1
127.0.0.1:6379> lpush key2 2
(integer) 2
127.0.0.1:6379> keys *
1) "key1"
2) "key2"
127.0.0.1:6379> info keyspace
# Keyspace
db0:keys=2,expires=0,avg_ttl=0

List all values in key2

127.0.0.1:6379> lrange key2 0 -1
1) "2"
2) "1"

Do FLUSHDB

127.0.0.1:6379> flushdb
OK

List keys and databases

127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> info keyspace
# Keyspace
user9869932
  • 6,571
  • 3
  • 55
  • 49
2

This works for me: redis-cli KEYS \* | xargs --max-procs=16 -L 100 redis-cli DEL

It list all Keys in redis, then pass using xargs to redis-cli DEL, using max 100 Keys per command, but running 16 command at time, very fast and useful when there is not FLUSHDB or FLUSHALL due to security reasons, for example when using Redis from Bitnami in Docker or Kubernetes. Also, it doesn't require any additional programming language and it just one line.

Jose Nobile
  • 3,243
  • 4
  • 23
  • 30
  • KEYS is a dangerous command in a large database. Firstly, it can be very slow. Secondly, the list of keys can be a hugh amount of data to transfer to the client. – Viktor Söderqvist Feb 02 '22 at 15:32
  • @ViktorSöderqvist Slow: Yes. Some MB to transfer to the client: Yes. Dangerous? I don't think so. This is the solution when there is not full access to Redis – Jose Nobile Feb 08 '22 at 20:07
  • Well, KEYS can affect the performance of your application, but if you're going to delete all keys anyway, that's not an issue. It is flagged as `@dangerous` (see `COMMAND INFO KEYS`). – Viktor Söderqvist Feb 23 '22 at 13:38
  • 1
    A great solution. It's worth noting, however, that in certain applications it can lead to inconsistent states during script execution, as it's not an atomic operation like `FLUSHDB`. For the vast majority, I think this wouldn't be a problem, but for the other cases, it's better to be cautious. – Marcelo Barros Jul 25 '23 at 21:12
1

Your questions seems to be about deleting entire keys in a database. In this case you should try:

  1. Connect to redis. You can use the command redis-cli (if running on port 6379), else you will have to specify the port number also.
  2. Select your database (command select {Index})
  3. Execute the command flushdb

If you want to flush keys in all databases, then you should try flushall.

anothernode
  • 5,100
  • 13
  • 43
  • 62
1

you can use following approach in python

def redis_clear_cache(self):

    try:
        redis_keys = self.redis_client.keys('*')
    except Exception as e:
        # print('redis_client.keys() raised exception => ' + str(e))
        return 1

    try:
        if len(redis_keys) != 0:
            self.redis_client.delete(*redis_keys)
    except Exception as e:
        # print('redis_client.delete() raised exception => ' + str(e))
        return 1

    # print("cleared cache")
    return 0
AbhiK
  • 247
  • 3
  • 19
1

If you want to clear redis in windows: find redis-cli in

C:\Program Files\Redis and run FLUSHALL command.

Flash Noob
  • 352
  • 3
  • 7
0

Its better if you can have RDM (Redis Desktop Manager). You can connect to your redis server by creating a new connection in RDM.

Once its connected you can check the live data, also you can play around with any redis command.

Opening a cli in RDM.

1) Right click on the connection you will see a console option, just click on it a new console window will open at the bottom of RDM.

Coming back to your question FLUSHALL is the command, you can simply type FLUSHALL in the redis cli.

Moreover if you want to know about any redis command and its proper usage, go to link below. https://redis.io/commands.

0

There are different approaches. If you want to do this from remote, issue flushall to that instance, through command line tool redis-cli or whatever tools i.e. telnet, a programming language SDK. Or just log in that server, kill the process, delete its dump.rdb file and appendonly.aof(backup them before deletion).

0

If you are using Java then from the documentation, you can use any one of them based on your use case.

/**
 * Remove all keys from all databases.
 *
 * @return String simple-string-reply
 */
String flushall();

/**
 * Remove all keys asynchronously from all databases.
 *
 * @return String simple-string-reply
 */
String flushallAsync();

/**
 * Remove all keys from the current database.
 *
 * @return String simple-string-reply
 */
String flushdb();

/**
 * Remove all keys asynchronously from the current database.
 *
 * @return String simple-string-reply
 */
String flushdbAsync();

Code:

RedisAdvancedClusterCommands syncCommands = // get sync() or async() commands 
syncCommands.flushdb();

Read more: https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster

roottraveller
  • 7,942
  • 7
  • 60
  • 65
0

For anyone wondering how to do this in C# it's the same as the answer provided for Python for this same question.

I am using StackExchange.Redis v2.2.88 for a dot net (core) 5 project. I only need to clear my keys for integration testing and I have no purpose to do this in production.

I checked what is available in intellisense and I don't see a stock way to do this with the existing API. I imagine this is intentional and by design. Luckily the API does expose an Execute method.

I tested this by doing the following:

  1. Opened up a command window. I am using docker, so I did it through docker.

  2. Type in redis-cli which starts the CLI

  3. Type in KEYS * and it shows me all of my keys so I can verify they exist before and after executing the following code below:

    //Don't abuse this, use with caution var cache = ConnectionMultiplexer.Connect( new ConfigurationOptions { EndPoints = { "localhost:6379" } });

    var db = _cache.GetDatabase();

    db.Execute("flushdb");

  4. Type in KEYS * again and view that it's empty.

Hope this helps anyone looking for it.

dyslexicanaboko
  • 4,215
  • 2
  • 37
  • 43