Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis Stack Exchange how to delete or get keys by pattern

I installed Stack Exchange redis client in C#. I can only delete one key or array of keys but I don't know how to delete keys with prefix. Or another solution can be first get all keys by pattern and then delete them. But I don't know how to get keys by pattern too.

like image 632
Robert Avatar asked Oct 21 '14 14:10

Robert


People also ask

How do I delete all keys matching a pattern in Redis?

Redis does not offer a way to bulk delete keys. You can however use redis-cli and a little bit of command line magic to bulk delete keys without blocking redis. This command will delete all keys matching users:* If you are in redis 4.0 or above, you can use the unlink command instead to delete keys in the background.

Which command is used to delete the key in Redis?

Redis DEL command is used to delete the existing key in Redis.

How do I flush all Redis?

To clear data of a DCS Redis 4.0 or 5.0 instance, you can run the FLUSHDB or FLUSHALL command in redis-cli, use the data clearing function on the DCS console, or run the FLUSHDB command on Web CLI. To clear data of a Redis Cluster instance, run the FLUSHDB or FLUSHALL command on every shard of the instance.

How many keys can Redis store?

Redis can handle up to 2^32 keys, and was tested in practice to handle at least 250 million keys per instance. Every hash, list, set, and sorted set, can hold 2^32 elements. In other words your limit is likely the available memory in your system.


2 Answers

You can do as the following to batch delete items from redis cache. (StackExchange.Redis.StrongName v1.0.488)

foreach (var ep in _muxer.GetEndPoints())
{
    var server = _muxer.GetServer(ep);
    var keys = server.Keys(database: _redisDatabase, pattern: pattern + "*").ToArray();
    _db.KeyDeleteAsync(keys);
}

_muxer is instance of ConnectionMultiplexer

It does not delete by pattern as you asked but much faster than deleting each key separately.

like image 169
Kerem Demirer Avatar answered Sep 26 '22 15:09

Kerem Demirer


Deletion is separate by key, unless you are flushing the entire database.

Key scanning is readily available on the IServer API, and is discussed much more here: https://stackexchange.github.io/StackExchange.Redis/KeysScan

However, it should still usually be avoided in production - that isn't the intended use-case for redis.

like image 42
Marc Gravell Avatar answered Sep 24 '22 15:09

Marc Gravell