Posted by: AJ Welch
- Most (But Not All) Objects Use a Key
- Using Namespaces
- Retrieving All Existing Keys
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 basickey/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 allkeys
from a Redis database with some simple commands.
Most (but not all) objects use a key
For the vast majority of data storage with Redis, data will be stored in a simplekey/value
pair. This is best shown through theredis-cli
(command line interface) usingGETandSETcommands.
For example, we may want to store some information aboutbooks
, such as thetitle
andauthor
of a few of our favorites.
>SETtitle"TheHobbit"
OK
>SETauthor"J.R.R.Tolkien"
OK
Thetitle
andauthor
are thekeys
we’ve set and the actual string values were specified after. So we can view them withGET
, like so:
>GETtitle
"TheHobbit"
>GETauthor
"J.R.R.Tolkien"
Using namespaces
That’s all well and good, but how do we add another book? We can’t reuse the sametitle
andauthor
keys or we’ll overwrite the existing data. Instead, we can use namespace syntax by using a:
separator and giving eachtitle
orauthor
entry a unique numerickey
:
>SETtitle:1"TheHobbit"
OK
>SETauthor:1"J.R.R.Tolkien"
OK
>SETtitle:2"TheSilmarillion"
OK
>SETauthor:2"TheSilmarillion"
OK
Now usingGET
requires adding the unique numerickey
as well:
>GETtitle:1
"TheHobbit"
>GETtitle:2
"TheSilmarillion"
Retrieving all existing keys
As it turns out, everySET
command we issued above created a new, uniquekey
within our Redis database. To get a list of all currentkeys
that exist, simply use theKEYScommand:
>KEYS*
1)"title:1"
2)"title:2"
3)"title"
4)"author:2"
5)"author"
6)"author:1"
By followingKEYS
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 originaltitle
andauthor
keys but also the four enumerated versions that followed as well.
The syntax followingKEYS
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'title'
:
>KEYS*title*
1)"title:1"
2)"title:2"
3)"title"
CAUTION: As mentioned in the official documentation, it is advisable to avoid using theKEYS
command on very large databases, but in particular avoid using it in a production environment. SinceKEYS
is returning potentially every key in the system, this can have a dramatic negative impact on performance.