How can I get the count of keys in redis?

16,971

Solution 1

You can use DBSIZE or INFO KEYSPACE

But if you want all the keys with a certain pattern in the name you need to use KEYS or SCAN And you need to pay attention to KEYS, running it in production can affect the performance so it should be used with caution.

Solution 2

DBSIZE Return the number of keys in the database

enter image description here

http://redis.io/commands/dbsize

Solution 3

Both (evil) KEYS and the much preferred SCAN do not return counts, only key names. You could wrap them in a Lua script to just return the count.

However.

Doing KEYS (or SCAN) in real time is very expensive in terms of performance - it means that you're iterating over the entire keyspace. What you want to do is keep the result ready beforehand, and then just fetch it. Usually in such cases, you'd use a Redis Set in which you'd store each relevant key name - SADD to it whenever you create a key that matches the patter *products* and delete from it whenever a key is removed.

But.

Since you're only interesting in a count, you can replace that Set with a simple counter.

Solution 4

Use this command line:

redis-cli --scan --pattern '*_products_*' | wc -l
Share:
16,971
Admin
Author by

Admin

Updated on July 23, 2022

Comments

  • Admin
    Admin almost 2 years

    I can get some keys with this command:

    keys *_products_*
    

    However that command returns all the keys, where I just need the count of those. How can I get It?