How to Get All Keys in Redis
Like other non-relational database engines, wrapping your mind around how Redis handles data structures and associations can sometimes be difficult. This is particularly true when Redis is compared to a more traditional relational databases with quarantined tables, each containing multiple rows and columns to house data.
Since Redis is non-relational, everything in the system is configured with basic
key/value pairs at the simplest level. During development in particular, it can be tricky to keep track of everything that exists in the database already, so in this brief tutorial we'll cover the method for retrieving all
keys from a Redis database with some simple commands.
Most (But Not All) Objects Use a Key
For example, we may want to store some information about
books, such as the
author of a few of our favorites.
> SET title "The Hobbit" OK > SET author "J.R.R. Tolkien" OK
author are the
keys we've set and the actual string values were specified after. So we can view them with
GET, like so:
> GET title "The Hobbit" > GET author "J.R.R. Tolkien"
That's all well and good, but how do we add another book? We can't reuse the same
author keys or we'll overwrite the existing data. Instead, we can use namespace syntax by using a
: separator and giving each
author entry a unique numeric
> SET title:1 "The Hobbit" OK > SET author:1 "J.R.R. Tolkien" OK > SET title:2 "The Silmarillion" OK > SET author:2 "The Silmarillion" OK
GET requires adding the unique numeric
key as well:
> GET title:1 "The Hobbit" > GET title:2 "The Silmarillion"
Retrieving All Existing Keys
As it turns out, every
SET command we issued above created a new, unique
key within our Redis database. To get a list of all current
keys that exist, simply use the
> KEYS * 1) "title:1" 2) "title:2" 3) "title" 4) "author:2" 5) "author" 6) "author:1"
KEYS with an asterisk (
*) -- which acts as a wildcard search -- we're asking Redis to retrieve all keys in the system. Thus, we not only see our two original
author keys but also the four enumerated versions that followed as well.
The syntax following
KEYS can be used to search for specific words or phrases within the key, or the exact match as well. Here we want all keys that contain the text
> KEYS *title* 1) "title:1" 2) "title:2" 3) "title"
CAUTION: As mentioned in the official documentation, it is advisable to avoid using the
KEYS command on very large databases, but in particular avoid using it in a production environment. Since
KEYS is returning potentially every key in the system, this can have a dramatic negative impact on performance.