Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the count of keys in redis?

Tags:

redis

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?

like image 658
Mario Alonso Martinez Leandro Avatar asked Nov 09 '15 21:11

Mario Alonso Martinez Leandro


People also ask

How can I get total number of keys in Redis?

The first command you can use to get the total number of keys in a Redis database is the DBSIZE command. This simple command should return the total number of keys in a selected database as an integer value. The above example command shows that there are 203 keys in the database at index 10.

How can I see all Redis keys?

To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.

How many keys are present inside the database Redis?

Redis can handle up to 2^32 keys, and was tested in practice to handle at least 250 million keys per instance. Every hash, list, set, and sorted set, can hold 2^32 elements.


4 Answers

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.

like image 149
Liviu Costea Avatar answered Oct 27 '22 03:10

Liviu Costea


DBSIZE Return the number of keys in the database

enter image description here

http://redis.io/commands/dbsize

like image 23
Cristiana Chavez Avatar answered Oct 27 '22 04:10

Cristiana Chavez


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.

like image 34
Itamar Haber Avatar answered Oct 27 '22 03:10

Itamar Haber


Use this command line:

redis-cli --scan --pattern '*_products_*' | wc -l
like image 24
Pankaj Chauhan Avatar answered Oct 27 '22 03:10

Pankaj Chauhan