Redis Stack Exchange how to delete or get keys by pattern
Solution 1
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.
Solution 2
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.
Robert
Updated on July 05, 2022Comments
-
Robert almost 2 years
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.
-
MaurGi over 6 yearsHow 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 ?
-
Kerem Demirer over 6 yearsHaven't tried it but I think you should invoke the same servers which used in single delete methods.
-
ErroneousFatality over 5 yearsYour documentation link is dead.
-
Marc Gravell over 5 years@ErroneousFatality fixed, ta
-
Ali Karaca almost 3 yearsAlso reader should consider that there may be another databases if using cluster(_redisDatabase default is 0)
-
Anton Semenov over 2 yearsIt 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.
-
ScubaSteve over 2 yearsWhat's the DI for
_muxer
? I am usingservices.AddStackExchangeRedisCache
and tried DIingConnectionMultiplexer
, but it comes back as null. -
Kerem Demirer over 2 yearsI've been using this approach for old .net and am not sure how it's registered in .netcore. This may help maybe: stackoverflow.com/questions/56272957/…