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,753
  • 72
  • 57
  • 129
  • 2,571
  • 10
  • 63
  • 95

2 Answers2


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();

_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,186
  • 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
  • How do you get the _db ? ToArray() also doesn't seem to exist on the current version of the driver. – JKJ Sep 06 '22 at 13:13
  • the database comes from the connection so presumably you can: `_db = _muxer.GetDatabase();` you can read through how it's done in the MS wrapper: https://source.dot.net/#Microsoft.Extensions.Caching.StackExchangeRedis/RedisCache.cs and it's mentioned in the docs: https://stackexchange.github.io/StackExchange.Redis/Basics – more urgent jest Jan 16 '23 at 03:04

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900