In this short tutorial, we’ll take a look at different ways to list all the databases available in Redis.
2. Listing All Databases
In the first place, the number of databases in Redis is fixed. Therefore, we can extract this information from the configuration file with a simple grep command:
$ cat redis.conf | grep databases databases 16
But what if we don’t have access to the configuration file? In this case, we can get the information we need by reading the configuration at runtime via the redis-cli:
127.0.0.1:6379> CONFIG GET databases 1) "databases" 2) "16"
Lastly, even though it’s more suitable for low-level applications, we can use the Redis Serialization Protocol (RESP) through a telnet connection:
$ telnet 127.0.0.1 6379 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. *3 $6 CONFIG $3 GET $9 databases *2 $9 databases $2 16
3. Listing All Databases With Entries
Sometimes we’ll want to get more information about the databases that contain keys. In order to do that, we can take advantage of the Redis INFO command, used to get information and statistics about the server. Here, we specifically want to focus our attention in the keyspace section, which contains database-related data:
127.0.0.1:6379> INFO keyspace # Keyspace db0:keys=2,expires=0,avg_ttl=0 db1:keys=4,expires=0,avg_ttl=0 db2:keys=9,expires=0,avg_ttl=0
The output lists the databases containing at least one key, along with a few statistics:
- number of keys contained
- number of keys with expiration
- keys’ average time-to-live
To sum up, this article went through different ways of listing databases in Redis. As we’ve seen, there are different solutions, and which one we choose really depends on what we’re trying to achieve.
A grep is generally the best option if we have access to the config file. Otherwise, we can use the redis-cli. RESP is not usually a good choice unless we’re building an application that needs a low-level protocol. Finally, the INFO command is useful if we want to retrieve only databases that contain keys.