Redis is a key-based data structure storage system. This a key-value storage system, where we don’t have any table or rows or columns like a relational database.
The whole modeling/storing/retrieving of data depends on the key. So naming the key becomes very important.
Here is how to effectively name keys in a Redis database-
Redis Key Naming Convention
Empty string is a valid key name in Redis.
Key names are binary safe, so we can use binary sequences in the Redis key name.
Maximum allowed size of a key in Redis is 512MB.
Maximum number of keys that Redis can handle is 2^32.
Here are the things to consider while naming a Redis key-
- Redis keys are strings. Any valid string is fine, including empty string and binary sequences are valid keys.
- Do not use a very long key. A very long key name will make it expensive while managing data and comparing keys.
- Do not name it too short. Make sure the key is readable and expressive. For example, for storing the user name, instead of naming it like u101nm, use user:101:name. Or for product discount use product:200:discount, instead of p200d.
- As a standard, use the format object_type:object_id(i.e. user:200, customer:1001) for storing an object. Or, for storing a property of an object object_type:object_id:object_property_name (i.e. product:1001:sku, product:2001:price, user:200:name)
The following commands are the most used and useful Redis commands for managing key and/or value.
Here we have discussed commands – KEYS, GET, SET, DEL, EXISTS, TYPE, EXPIRE, TTL, PERSIST.
Redis Command: KEYS – retrieve keys
Signature:
KEYS <pattern>
Usage:
Get the list of all keys in the database that matches the provided pattern(<pattern>)
Use with care in a production database. As, getting all the keys in a database with a huge dataset is an expensive task, and can harm the performance of the database in production.
Pattern Details:
The <pattern> in the command follows the Glob-style patterns. For example-
Pattern | Meaning |
---|---|
* | Matches anything, as the asterisk means any character any number of times. |
big* | Any string that starts with “big” and then has any characters. i.e. bigb, bigbox, bigboxcode |
b[a-z]g | Any string that starts with “b”, then has 1 character between a to z, and then has “g” at the end. i.e. big, bag, bcg, bmg |
b[ai]g | Any string that starts with “b”, then has any of “a” or “i” once, and then has “g” at the end. i.e. bag, big (only these 2 are possible in this case) |
b[a-z]*g | Key name that starts with “b”, then has character between “a” to “z” any number of times, and then ends with “g”. i.e. bag, baaaaaag, babcdg, bworeinoweirnonfoiwejriidjfljasldkfjasldg |
b[^ai]g | Key name that starts with “b”, then has any character other than “a” and “i”, then has “g” at the end. i.e. bbg, bng, byg, bcg |
b?g | Key name that starts with “b”, ends with “g” and has any 1 character in the middle. i.e. bag, bbg, bcg, bdg |
c??e | String starts with “c”, and ends with “e”. And has 2 characters(any character) in between “c” and “e”. i.e. cabe, code, cone, cute, cure |
c[a-z]?de | String that starts with “c”, ends with “de”. And has any character between “a” to “z” once. i.e. cade, code, cnge |
These patterns follow the Glob style.
Then patterns are case sensitive.
Use a backslash(\) to escape any special character.
Examples:
Check the example below-
127.0.0.1:6379> keys *
1) "a"
2) "site:domain"
3) "site:topic"
4) "somekey"
5) "site:name"
127.0.0.1:6379> keys site:*
1) "site:domain"
2) "site:topic"
3) "site:name"
127.0.0.1:6379> keys SIte*
(empty array)
127.0.0.1:6379> keys s???k*
1) "somekey"
Redis Command: GET – retrieve a value
Signature:
GET <key>
Usage:
Get value of the <key>.
Return Type:
Return value | Case for the return value |
---|---|
Value saved for the key | When the key exits, and key has a valid value saved for it. |
nil | When the key does not exist. |
error | When the saved value for the key is not a valid string. |
Examples:
127.0.0.1:6379> get a
"dd"
127.0.0.1:6379> get wrongkey
(nil)
127.0.0.1:6379> get site:domain
"bigboxcode.com"
127.0.0.1:6379> get site:wrong
(nil)
Redis Command: SET – set key/value
Signature:
Simple signature-
SET <key> <value>
Complete signature-
SET <key> <value> [NX | XX] [GET] [EX <seconds> | PX <milliseconds> | EXAT <unix-time-seconds> | PXAT <unix-time-milliseconds> | KEEPTTL]
Options:
Option | Description |
---|---|
NX | Only perform the set operation if the key doesn’t already exist. |
XX | Only perform the set operation if the key already exists. |
EX <seconds> | Expire time in seconds. |
PX <milliseconds> | Expire time in miliseconds. |
EXAT <unix-time-seconds> | Unix timestamp in seconds when the key/value pair will be expired. |
PXAT <unix-time-miliseconds> | Unix timestamp in milliseconds when the key/value pair will be expired. |
KEEPTTL | Keep the set TTL. |
GET | Return the value for the key, that was already existing(old value). nil is returned if the key did not exist. |
Usage:
Set value for a key.
- If the key does not already exist, then it will be created and the value will be set.
- If the key already exists then the value is replaced with the newly provided value.
- If the key is already existing and has a TTL, then replace the TTL upon successful command execution.
Return Type:
Return value | Case for the return value |
---|---|
OK | Successfully execution. |
nil | If the command failed for some reason. Possible reason- for NX or XX options. |
Examples:
# set a key/value
127.0.0.1:6379> set firstkey "some value"
OK
# check the key/value
127.0.0.1:6379> get firstkey
"some value"
# set key/value with expire time of 10 seconds
127.0.0.1:6379> set secondkey "another value" ex 10
OK
# check within 10 seconds of setting, and the we will get the value
127.0.0.1:6379> get secondkey
"another value"
# check after 10 seconds of setting the value, and the value does not exist
127.0.0.1:6379> get secondkey
(nil)
# Try setting somekey and check if it not exists already
127.0.0.1:6379> set somekey newval nx
(nil)
127.0.0.1:6379> set differentkey newval nx
OK
# Set key/value only if that exists
127.0.0.1:6379> set somekey newval xx
OK
Redis Command: DEL – destroy key/value
Signature:
DEL <key> [<anotehr_key> … ]
Usage:
Delete specific key or keys.
Return Type:
The number of keys that are deleted.
Examples:
# Set some vlaues
127.0.0.1:6379> set firstkey "value 123"
OK
127.0.0.1:6379> set secondkey "value 345"
OK
127.0.0.1:6379> set thirdkey "9876"
OK
# Delete firstkey. The command executes successfully
127.0.0.1:6379> del firstkey
(integer) 1
# Try to get firstkey, that returns error as the key no longer exists.
127.0.0.1:6379> get firstkey
(nil)
# Delete secondkey adn thirdkey. Both are deleted successfully.
127.0.0.1:6379> del secondkey thirdkey
(integer) 2
# Now try to delete secondkey again. It returns 0, s the secondkey does not exist anymore
127.0.0.1:6379> del secondkey
(integer) 0
A similar command is “UNLINK <key> [<another_key> … ]“. The Unlink command works like DEL, the difference is in the process.
Del deletes keys one by one, synchronously, and makes it a blocking command. That makes the memory reclaiming of the DEL command slower.
On the other hand, the UNLINK command is non-blocking, as the processing is done synchronously in different threads. In UNLINK the command the actual removal operation happens asynchronously, so the memory reclaiming is much faster than DEL.
Redis Command: EXISTS – check existence
Signature:
EXISTS <key> [<another_key> … ]
Usage:
Check if the key exists in keyspace or not.
Return Value:
Number(integer) of the keys that exist in the database.
If the same key name is passed twice and the key exists in the database, then 2 is returned. So the command does not consider the unique number of keys, which are passed.
Examples:
127.0.0.1:6379> keys *
1) "a"
2) "site:domain"
3) "b"
4) "site:topic"
5) "somekey"
6) "site:name"
127.0.0.1:6379> exists a
(integer) 1
127.0.0.1:6379> exists a b somekey
(integer) 3
127.0.0.1:6379> exists a a b somekey b
(integer) 5
127.0.0.1:6379> exists wrongkey
(integer) 0
127.0.0.1:6379> exists a wrongkey
(integer) 1
Redis Command: TYPE – check value type
Signature:
TYPE <key>
Usage:
Check the type of value saved in the key.
Return Value:
Returned Value | Description |
---|---|
String representation of the type of value | The type name(string) of the value. i.e. string, list, set, hash, stream. |
none | If the key does not exist. |
Examples:
127.0.0.1:6379> type somekey
string
127.0.0.1:6379> type hash1
hash
127.0.0.1:6379> type list1
list
127.0.0.1:6379> type wrongkey
none
Redis Command: RENAME– rename key
Signature:
RENAME <key> <new_key_name>
Usage:
Rename an existing key.
If the <new_key_name> already exists, then this command overrites the <new_key_name>. In the background, this RENAME command deletes the existing key <new_key_name> first and then creates a new entry with the <new_key_name>. So, if the value is large, then deleting and recreating the entry can cause performance issues.
Return Value:
Returned Value | Description |
---|---|
OK | If rename of the key is successful. |
error | If the key does not exist. |
Examples:
127.0.0.1:6379> set firstkey 99
OK
# Rename key
127.0.0.1:6379> rename firstkey changedkey
OK
# Try to rename the same key. We get error as the "firstkey" does not exist anymore
127.0.0.1:6379> rename firstkey changedkey
(error) ERR no such key
# Let's check another example
127.0.0.1:6379> set firstkey 100
OK
127.0.0.1:6379> set secondkey 200
OK
# Let's rename the firstkey to second key
127.0.0.1:6379> rename firstkey secondkey
OK
# After rename the firstkey deos not exist any more
127.0.0.1:6379> get firstkey
(nil)
# After rename the secondkey has the value(100) of first key
127.0.0.1:6379> get secondkey
"100"
A similar command is “RENAMEX <key> <new_key_name>“. In RENAMEX the key name is changed only if the key <new_key_name> does not exist. If the <new_key_name> already exists then the command returns Zero(0).
Redis Command: EXPIRE – set expiry time
Signature:
Simple use of the command-
EXPIRE <key> <seconds>
Full signature of the command-
EXPIRE <key> <seconds> [NX | XX | GT | LT]
Usage:
Set expiration time(timeout) for a key.
Options:
Option | Description |
---|---|
NX | Only when there is no expiry time set already for the key. |
XX | Only when the expiry time is already set for the key. |
GT | Only when the new expiry time is greater that the existing one. |
LT | Only when the new expiry time is less than the existing one. |
Return Value:
An integer value is returned-
Return Value | Description |
---|---|
1 | If the command is successful (the expiry time is set properly) |
0 | If the command is not successful, for reasons like- key does not exist or for the “GT” or “LT” option the time-limit does not satisfy. |
Examples:
127.0.0.1:6379> set firstkey "first value"
OK
127.0.0.1:6379> expire firstkey 10
(integer) 1
127.0.0.1:6379> ttl firstkey
(integer) 4
127.0.0.1:6379> set firstkey "first value"
OK
127.0.0.1:6379> expire firstkey 20
(integer) 1
127.0.0.1:6379> expire firstkey 2 XX
(integer) 1
127.0.0.1:6379> expire firstkey 200 LT
(integer) 1
127.0.0.1:6379> ttl firstkey
(integer) 194
A similar command is “PEXPIRE<key> <milliseconds> [NX|XX|GT|LT]“. In the PEXPIRE command, we set the expiry time in milliseconds.
Another similar command is “EXPIREAT<key> <unix_time_in_seconds> [NX|XX|GT|LT]“. In the EXPIREAT command, we set an absolute UNIX timestamp (seconds since Jan 1, 1970) for when the key should expire.
Another similar command is “PEXPIREAT<key> <unix_time_in_milliseconds> [NX|XX|GT|LT]“. In the PEXPIREAT command, we set an absolute UNIX timestamp (milliseconds since Jan 1, 1970) for when the key should expire.
Redis Command: TTL – get remaining time
Signature:
TTL <key>
Usage:
Get the remaining time for the key expiry timeout, in seconds.
Return Value:
An integer value is returned-
Return Value | Description |
---|---|
Some positive interger | Some positive integer |
-1 | If the key exists but does not have any expiery time associated. |
-2 | If the key does not exist. |
Examples:
#set value with expiery time with 20 seconds
127.0.0.1:6379> set firstkey "somevalue" ex 20
OK
# check TTL
127.0.0.1:6379> ttl firstkey
(integer) 15
127.0.0.1:6379> ttl firstkey
(integer) 10
127.0.0.1:6379> ttl firstkey
(integer) 8
127.0.0.1:6379> ttl firstkey
(integer) 2
127.0.0.1:6379> ttl firstkey
(integer) 1
# TTL response when key is removed for timeout
127.0.0.1:6379> ttl firstkey
(integer) -2
# set the value without any TTL
127.0.0.1:6379> set firstkey "some value"
OK
# response when no TTL is associated
127.0.0.1:6379> ttl firstkey
(integer) -1
A similar command is “PTTL <key>“. The PTTL command returns the remaining time in milliseconds.
Redis Command: PERSIST – remove timeout
Signature:
PERSIST <key>
Usage:
Remove the timeout from the key. This command makes the key to persist with no more timeout.
Return Value:
An integer value is returned-
Return Value | Description |
---|---|
1 | If the command is successful, and timeout is removed from the key. |
0 | If there is an error while command execution- the key does not exist, or the key does not have any timeout associated. |
Examples:
# Set value with 200 seconds timeout
127.0.0.1:6379> set firstkey "some value" ex 200
OK
# Check the ttl
127.0.0.1:6379> ttl firstkey
(integer) 196
# Persist to remove the timeout
127.0.0.1:6379> persist firstkey
(integer) 1
# Check the ttl again. -1 is returned to indicate that, it does not have any expiry associated
127.0.0.1:6379> ttl firstkey
(integer) -1
127.0.0.1:6379> set firstkey 99
OK
# Then if we try to persist again then return value is 0 as not expiery time is associated with it
127.0.0.1:6379> persist firstkey
(integer) 0
# Let's try to persist a non existing key, 0 is returned
127.0.0.1:6379> persist wrongkey
(integer) 0