Redis Basic Commands Tutorial
In this Redis tutorial we learn the basic commands of Redis like KEYS, SET & GET, DEL, FLUSHALL, EXISTS, DUMP. We also go over the asterisk pattern and key expiration.
Basic Redis Commands
We communicate with the Redis server by using commands to perform operations on the database.
A command has one or more arguments like keys and values that help us perform these operations.
In this lesson, we cover only common and basic commands.
The KEYS command
The KEYS command takes in a pattern as an argument and returns all the keys that matches that pattern.
To return a list of all the keys in the database, we use the * (asterisk) symbol.
If there are no keys present, it will return one of the following messages.
(empty list or set) (empty array)
The SET & GET commands
As mentioned before, Redis is a key:value store. There are no rows and columns like in a relational database, only keys and their corresponding values.
We can set a key:value pair by using the SET command. This command takes the key name and its corresponding value as arguments.
SET name value
SET fName John
In the example above we create a new key with the name fName and the value John.
We can get the value of a key by using the GET command. This command takes the key name as an argument.
In the example above we access the value of fName, which is John.
The SET command is also used to update the value of a key.
SET fName Jane
If we access the key now, it will show the new value.
Sometimes, this behavior isn’t what we want. Redis allows us to set a value only if the key doesn’t exist yet with the SETNX command.
SETNX fName John
If we try to change the fName key with this command, it won’t work because it already exists.
The SETNX command allows us to work a little more defensively, we won’t be able to overwrite any data accidentally.
The APPEND command
Redis allows us to append data to the end of values with the APPEND command. This command takes the key name and the value to append as arguments.
APPEND name value
APPEND fName " Doe"
We wrap the value in quotes because we want a space to separate the name and surname.
If we check the value of the key now, we can see that it appended the surname.
The DEL command
If we want to delete a key and its value, we can use the DEL command. This command takes the key name as an argument.
In the example above we delete the fName key from the database.
The output message is a number that shows how many records were affected.
This means we successfully deleted the key and its value. We can test it by running the GET command.
This time the output message shows nil, which means the key does not exist.
If we pass in a key that doesn’t exist, no keys will be deleted.
Because the key doesn’t exist, Redis can’t update any records and the output message will show 0.
The asterisk * pattern
As mentioned before, the * symbol will show a list of all the keys in the database.
To demonstrate, let’s add multiple keys to the database.
SET fname John SET lname Doe SET age 31
Now when we use the * as a pattern for the KEYS command, it will show this list of keys.
1) "lname" 2) "fname" 3) "age"
The asterisk symbol represents anything. We can use it with more patterns to help us refine our search for keys.
For example, if we add * after the word ‘age’, it will show all the keys that start with the word ‘age’.
It doesn’t have to be a full word, it can be part of a word or even a single letter.
The command reads: a + anything after it
When we add a * before a word or letter, it will show all the keys that end with that word or letter.
1) "lname" 2) "fname" 3) "age"
Because all of our key names end with an e, it will return all of them.
The command reads: anything that ends with e
When we add a * before and after the word or letter, it will show all the keys that contain that word or letter.
The command reads: anything with g inside it
1) "lname" 2) "fname"
The command reads: anything with name inside it
The FLUSHALL command
The FLUSHALL command is used to clear all the databases on the server, removing all keys and values.
To demonstrate that the database was cleared, we can use the KEYS command.
The FLUSHALL command returns only after the database is fully cleared. Depending on the size of the database, this may take some time, which is why we can let it return as soon as the command is received by the server with ASYNC .
We can set an expiration time on keys so that after a certain amount of time, they’re cleared from the database automatically.
As an example, let’s consider that we need to store session IDs that become invalid after a certain period of time. If we set an expiration time on that key, it will automatically delete the key when the time has passed.
To see if a key has an expiration on it, and when that time expires in seconds, we can use the TTL (Time To Live) command.
SET num 8 TTL num
In the example above we add a new key called num with a value of 8, then check its expiration with the TTL command.
The command returns a value of -1, which means that the key has no expiration time.
We can set an expiration on a key by using the EXPIRE command. This command takes the key name and time to expire in seconds as arguments.
EXPIRE name seconds
EXPIRE num 30
In the example above we specify that we want the num key to live for 30 seconds.
The output returns success. When we check the TTL again now, it will show how many seconds are left.
Once the key expires, the output will be different.
It’s important to remember that -1 means an expiration has not been set, whereas -2 means that a key with an expiration has reached the expiration time.
We can add an expiration time directly when creating the key with the SETEX command. This command accepts the name of the key, expiration in seconds, and then the value as arguments.
SETEX name seconds value
SETEX fName 30 John
The EXISTS command
We can check if a key exists with the EXISTS command. This command takes the key name as an argument.
Because the key was set with SETEX in the previous section, it expired and no longer exists.
If we SET the key and check if it exists again, it will show 1 in the output.
SET fName John EXISTS fName
The STRLEN command
We can check the length of the value stored in a key with the STRLEN command. This command takes the key name as an argument.
The output shows 4 because there are four characters in the name John.
If we do the same with a number, it will show the amount of digits in the number.
SET num 30 STRLEN num
The output shows 2 because there are two digits in the number 30.
The DUMP & RESTORE commands
We can serialize the value of a key in a Redis specific format by using the DUMP command. This command takes the key name as an argument.
SET fullName "John Doe" DUMP fullName
The serialized value can be restored in this or another database with the RESTORE command. This command takes the new key name, followed by a TTL value and the serialized value as arguments.
RESTORE name ttl serializedValue
If we specify 0 as the TTL expiration, the key will not have any expiration set.
If the key already exists, we can add the REPLACE modifier to command to replace the value in the key.
RESTORE name ttl serializedValue REPLACE
DEL fullName RESTORE name 0 "\x00\bJohn Doe\t\x00\x98\xf3~\x15\xa8\xc7\x8d}"
In the example above we first delete old fullName key, then restore the serialized one to a new key called name with no expiry.
The HELP command
Some commands allow us to get more information about their subcommands by using the HELP subcommand.
The example above will return the subcommands of the CLIENT command.
1) CLIENT <subcommand> arg arg ... arg. Subcommands are: 2) ID -- Return the ID of the current connection. 3) GETNAME -- Return the name of the current connection. 4) KILL <ip:port> -- Kill connection made from <ip:port>. 5) KILL <option> <value> [option value ...] -- Kill connections. Options are: 6) ADDR <ip:port> -- Kill connection made from <ip:port> 7) TYPE (normal|master|replica|pubsub) -- Kill connections by type. 8) USER <username> -- Kill connections authenticated with such user. 9) SKIPME (yes|no) -- Skip killing current connection (default: yes). 10) LIST [options ...] -- Return information about client connections. Options: 11) TYPE (normal|master|replica|pubsub) -- Return clients of specified type. 12) PAUSE <timeout> -- Suspend all Redis clients for <timout> milliseconds. 13) REPLY (on|off|skip) -- Control the replies sent to the current connection. 14) SETNAME <name> -- Assign the name <name> to the current connection. 15) UNBLOCK <clientid> [TIMEOUT|ERROR] -- Unblock the specified blocked client. 16) TRACKING (on|off) [REDIRECT <id>] [BCAST] [PREFIX first] [PREFIX second] [OPTIN] [OPTOUT]... -- Enable client keys tracking for client side caching. 17) GETREDIR -- Return the client ID we are redirecting to when tracking is enabled.