I am using Azure Redis and I cannot get this simple search to work
What am I doing wrong?
When I search for a specific key which I know is in the cache its not found?
private async Task DeleteAllKeysForProfileAsync(string profileId)
{
var endpoint = _connectionMultiplexer.GetEndPoints().First();
var pattern = $"*{profileId}*";
var keys = this._connectionMultiplexer.GetServer(endpoint).Keys(pattern: pattern);
foreach (var key in keys)
{
await _redisDatabase.KeyDeleteAsync(key);
}
}
Paul
Instead of KEYS
use SCAN
. In the above code does not explicitly use SCAN
, I suggest for better practices and performance, SCAN
is non-blocking and can handle larger datasets more efficiently.
I Refered this DOC for SCAN
and how do I use them.
the KEYS command as it only supports the following glob-style pattern and Lua script that you can use to find all keys.You are limited to querying all keys at once or one or more keys specified by their exact name. This usage pattern probably means you need a hash plus another data structure (e.g. set) to keep record of the interesting keys, or two or more separate hashes.
public class RedisServiceClassName
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly IDatabase _redisDatabaseName;
public RedisServiceClassName(IConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
_redisDatabaseName = _connectionMultiplexer.GetDatabase();
}
public async Task SetKeyAsync(string key, string value)
{
Console.WriteLine($"Setting key: {key} with value: {value}");
bool setResult = await _redisDatabaseName.StringSetAsync(key, value);
Console.WriteLine($"Set result: {setResult}");
}
public async Task DeleteAllKeysForProfileAsync(string profileId)
{
var endpoint = _connectionMultiplexer.GetEndPoints().First();
var server = _connectionMultiplexer.GetServer(endpoint);
var pattern = $"*{profileId}*";
var keys = server.Keys(database: _redisDatabaseName.Database, pattern: pattern);
Console.WriteLine($"Found {keys.Count()} keys matching pattern '{pattern}'.");
foreach (var key in keys)
{
Console.WriteLine($"Deleting key: {key}");
await _redisDatabaseName.KeyDeleteAsync(key);
}
}
}
public static class Program
{
public static async Task Main(string[] args)
{
var redisConnectionString = "AzureRadisNme.redis.cache.windows.net:6380,password=Password,ssl=True,abortConnect=False";
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(redisConnectionString);
var redisService = new RedisServiceClassName(connectionMultiplexer);
await redisService.SetKeyAsync("user:192a2b84-867b-495f-bd8a-2083e2c76036:profile", "User Profile Data for 007");
await redisService.SetKeyAsync("user:007:settings", "User Settings Data for 007");
string profileId = "192a2b84-867b-495f-bd8a-2083e2c7603";
await redisService.DeleteAllKeysForProfileAsync(profileId);
Console.WriteLine("Operation completed. Press any key to exit.");
Console.ReadKey();
}
}