skip to Main Content

I am trying to count the keys matching a pattern. I did get the returned keys from using the SCAN command. But instead of getting the keys array, I only want to get the count of the keys.

SCAN 0 MATCH tick:klays:umc:*

I am using this INCR to increment the key tick:klays:umc:278 like below:

INCR tick:klays:umc:*278
INCR tick:klays:umc:*260
INCR tick:klays:umc:*279

2

Answers


  1. From somewhere on the internet:

    KEYS vs SCAN

    The SCAN function was created to break up the blocking KEYS command which could present major issues when used in production. Many Redis users know too well the consequences of this slowdown on their production workloads. The KEYS command and SCAN command can search for all keys matching a certain pattern.

    In your scenario, it seems like you want the count of the keys that matches the given pattern. Meaning, you want them all at one go. If that is the case, you must be using KEYS command rather than SCAN.

    So, you might want to use keys & count the result in JavaScript.

    const keys = await client.keys('tick:klays:umc:*');
    const count = keys.length; // 280
    

    You must also remember that, KEYS is a blocking operation as mentioned above. So, be aware of the performance. If number of the keys can keep grow, you might want to keep a counter for them in redis.

    Login or Signup to reply.
  2. You could always use the INFO command. It returns stats on Redis, including how many keys there are:

    > SET foo bar
    OK
    > SET bar baz
    OK
    > SET baz qux
    OK
    127.0.0.1:6379> INFO KEYSPACE
    # Keyspace
    db0:keys=3,expires=0,avg_ttl=0
    

    You’ll have to do a bit of parsing, but the value is in there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search