2

So I'm using "StackExchange.Redis" and I was wondering if I can get multiple values by key pattern or by key list in order to have one trip to the redis cache and get all the data that I need.

I already tried to use "star" in the key when using the "GetObject" method something like this:

User user = RedisContext.Cache.GetObject("User*");

but this returns null.

And I also tried to get all the keys by pattern which did work but I couldn't get the values in one go, like this:

var endpoint = RedisContext.GetConnectionMultiplexer().GetEndPoints().First();
var keys = RedisContext.GetConnectionMultiplexer().GetServer(endpoint.ToString()).Keys(pattern: "User*");
List<string> keyList = new List<string>();
foreach (var _key in keys)
{
      keyList.Add(_key);
}

List<User> users = RedisContext.Cache.GetObjectsByTag<dynamic>(keyList.ToArray());

But this gives me an exception. Is there something that I'm missing?

1
  • I think RediSearch is the best option to get all keys by pattern. Please find more details at github.com/redis/nredisstack Commented May 4, 2023 at 21:45

1 Answer 1

3

Can you get multiple keys in one fell swoop?

Sort of answered here already

You can pass an array of RedisKeys into the StringGet or StringGetAsync methods on the IDatabase object - see the following example from nothing:

var muxer = ConnectionMultiplexer.Connect("localhost");

var db = muxer.GetDatabase();

db.StringSet("foo", "bar");
db.StringSet("baz", "foo");
db.StringSet("bar", "baz");

var result = await db.StringGetAsync(new RedisKey[]{"foo","bar","baz"});

foreach (var item in result)
{
    Console.WriteLine((string)item);
}

Can you get all the keys by pattern in one shot

You can, but shouldn't unless you want to build a secondary index. You could write a lua script to match a key pattern and then pull back all the keys with that pattern, but that will be horribly inefficient and dangerous as you would be committing to looking over your entire keyspace in one operation which is one of those things that can really hang a Redis Server.

What you can do is create a secondary index and search for the the keys matching a given pattern. This can either be done the traditional way, or you could use a module like RediSearch to help build them for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.