0

I'm trying to create a simple method in c# to get a count of keys in my Redis instance. In redis, I have my keys like:

mykey:1
mykey:2
mykey:3

By using redis-cli, I can run:

eval "return #redis.pcall('keys', 'mykey:*')" 0

and it returns:

(integer) 3

So, I build this function in c#:

public void GetThatCounter()
    {
        var script=LuaScript.Prepare("redis.pcall('keys', 'mykey:*')");
        var result=dbCache.ScriptEvaluate(script);
        Console.WriteLine("result"+result.ToString());
    }

However, the result contains "isnull:true", meaning there are no results...

(The function is obviously returing nothing now, I'm just using it as a test and breaking code excecution on debug, to dig inside the result variable with the Visual Studio editor)

Any help ?

5
  • There is no return statement in the C# embedded script. Maybe this is the cause ?
    – aureliar
    Commented Feb 5, 2021 at 9:44
  • Actually I was talking of the embedded lua script in the LuaScript.Prepare parameter, not the C# code...
    – aureliar
    Commented Feb 5, 2021 at 15:52
  • ouch... ok I deleted my useless comment and added the "return" to the lua script. Now it returns me an array with all the keys (key1, key2, key3) instead of just the count of the elements... ?!? Commented Feb 5, 2021 at 15:55
  • 1
    Have you also added the # symbol ? Which i guess gives the size of this array ?
    – aureliar
    Commented Feb 5, 2021 at 15:57
  • awesome !!! that solved the question! Commented Feb 5, 2021 at 15:59

1 Answer 1

0

Ok, thanks to Aureliar's comments, here is the final answers:

  • In order to get a result from a redis.pcall, you need to add a "return" before the redis.pcall
  • In order to get the size of the array only, you need to add a # before the redis.call
  • I also found that, in this case, you don't need a Lua script at all.

So the final function looks like this:

public int GetCount(string keyWithWildCards) //e.g. key:*
{           
 return (int)dbCache.ScriptEvaluate($"return #redis.pcall('keys', '{keyWithWildCards}')");
}

This will avoid to receive back millions of keys: the count will be made on redis side.

In case the pattern doesn't match any key, it will return 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.