19

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.

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Robert
  • 2,451
  • 10
  • 55
  • 79

2 Answers2

30

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.

Kerem Demirer
  • 1,106
  • 2
  • 13
  • 24
  • How does this work in a cluster? We are getting twice as many endpoints (including the slaves) and deleting too many keys, should we filter for server.IsSlave == false ? – MaurGi Sep 26 '17 at 21:44
  • Haven't tried it but I think you should invoke the same servers which used in single delete methods. – Kerem Demirer Nov 06 '17 at 05:01
  • Also reader should consider that there may be another databases if using cluster(_redisDatabase default is 0) – Ali Karaca Jul 12 '21 at 14:15
  • It works. One thing to add I had a problem slowing me with direct connections to master/slave nodes. For me helped disabling vpn on local machine or running the code on prod machines. IP addresses could not be resolved for some reason. – Anton Semenov Sep 29 '21 at 13:32
  • What's the DI for `_muxer`? I am using `services.AddStackExchangeRedisCache` and tried DIing `ConnectionMultiplexer`, but it comes back as null. – ScubaSteve Oct 12 '21 at 15:01
  • I've been using this approach for old .net and am not sure how it's registered in .netcore. This may help maybe: https://stackoverflow.com/questions/56272957/what-are-the-key-difference-in-using-redis-cache-via-connectionmultiplexer-and-a – Kerem Demirer Oct 26 '21 at 08:29
14

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.

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830