[redis] Print number of keys in Redis

Is there a way to print the number of keys in Redis?

I am aware of

keys *

But that seems slightly heavy weight. - Given that Redis is a key value store maybe this is the only way to do it. But I would still like to see something along the lines of

count keys *

This question is related to redis

The answer is


dbsize() returns the total number of keys.

You can quickly estimate the number of keys matching a given pattern by sampling keys at random, then checking what fraction of them matches the pattern.

Example in python; counting all keys starting with prefix_:

import redis
r = redis.StrictRedis(host = 'localhost', port=6379)
iter=1000
print 'Approximately', r.dbsize() * float(sum([r.randomkey().startswith('prefix_') for i in xrange(iter)])) / iter

Even iter=100 gives a decent estimate in my case, yet is very fast, compared to keys prefix_.

An improvement is to sample 1000 keys on every request, but keep the total count, so that after two requests you'll divide by 2000, after three requests you'll divide by 3000. Thus, if your application is interested in the total number of matching keys fairly often, then every time it will get closer and closer to the true value.


After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.


Since Redis 2.6, lua is supported, you can get number of wildcard keys like this

eval "return #redis.call('keys', 'prefix-*')" 0

see eval command


WARNING: Do not run this on a production machine.

On a Linux box:

redis-cli KEYS "*" | wc -l

Note: As mentioned in comments below, this is an O(N) operation, so on a large DB with many keys you should not use this. For smaller deployments, it should be fine.


eval "local count = redis.call('scan', 0, 'match', 'key:*:key', 'count', 10000) if count ~= 0 then return #count[2] end " 0

eval "local count = redis.call('sscan', 'key.key:all', 0, 'match', '*', 'count', 1000000) if count ~= 0 then return #count[2] end " 0

Go to redis-cli and use below command

info keyspace

It may help someone


DBSIZE returns the number of keys and it's easier to parse.

Downside: if a key has expired it may still count.

http://redis.io/commands/dbsize


For getting count total number of keys, use below command:

127.0.0.1:6379> DBSIZE