Redis Data Structures - Keys
Updated: Dec 24, 2020
In this post, we will have a detailed explanation about an essential piece in the world of Redis, keys.
Keys are the way you can access your data within Redis. They are unique and binary-safe values and can be anything like strings, numbers, or even binary data. The max size of a key is 512 Mb, but smaller keys are recommended. Bear in mind that key names are case sensitive.
It is a good practice to select a namespacing convention for your keys within your organization otherwise, you can get key name collisions. A typical convention is to use a colon as a separator ( customer:1 ) where the customer is your domain and 1 is your unique identifier.
Please follow my previous post to install a Redis instance and Redis-cli to access your instance.
To get all keys or keys filtered by a pattern, Redis provides two commands: KEYS and SCAN.
This command should not be used in production as it blocks the instance while iterating over all keys. Its main purpose is for debugging or other special operations. Use the star operator to filter your keys.
redis> keys *customer* 1) "customer:2" 2) "customer:1"
Time complexity: O(N) with N being the number of keys in the database.
On the other hand, SCAN is a safe command to be used in production. Nevertheless, it should be used carefully. SCAN uses a cursor to iterate through our set of keys, limiting the number of keys returned.
Syntax: SCAN cursorPosition [MATCH pattern] [COUNT count]
Let's try to get first two (count) customers (pattern)
redis> scan 0 match *customer* count 2 1) "3" 2) 1) "customer:1" 2) "customer:2"
Scan command returned "3", which means we need to scan again, starting from that position, to get the remaining customers.
redis> scan 3 match *customer* count 2 1) "0" 2) (empty array)
The cursor position returned is "0" which means no more results for that specific pattern.
Time complexity: O(1) for every call.
To remove a key or set of keys from our database, Redis offers two commands: DEL and UNLINK.
DEL key will remove a key from the memory, as a blocking operation. If a key does not exist, Redis will simply ignore it. The result of the command is the total number of keys deleted.
Example will delete two keys
redis> del customer:1 customer:2 (integer) 2
Time complexity: O(N) where N is the number of keys that will be removed.
UNLINK command is the main choice because is non-blocking. Command will "unlink" the key from keyspace and the memory associated will freed by an async process.
redis> UNLINK customer:1 customer:2 (integer) 2
Time complexity: O(1) for each key removed.