Redis - Hashes
Hashes in Redis work like objects in programming languages; it is a single key that can contain multiple field-value pairs inside it. The fields in the hash are unique.
Limitation with hashes
Hashes can only contains strings. You cannot nest more hashes inside hashes or have any other data types inside hashes.
Setting a field inside hash (HSET)
To set a field inside a hash (and to create the key if it does not not exist yet), the command HSET can be used. Learn more
Time Complexity: O(1) for each field / value pair added. O(N) if adding multiple.
Example usage:
Getting Hash Fields and their Values (HSCAN)
HKEYS
The HKEYS command was used in the past for listing the keys. It is no longer recommended to use the HKEYS command, as it blocks the whole database operation until it outputs the data and can cause massive problems in production environments with lots of data (it's slow and takes large amount of memory with large dataset). Use HSCAN instead.
The command HSCAN works like the SCAN, thus can be used to list all fields and their values inside a hash. It can take in the MATCH (filter) and COUNT (how many results to return) parameters for further customization. Learn more
Time Complexity: O(1) for the call. O(N) where N is the number of elements in the specified hash collection.
Example usage:
Defaults to 10
By default, when not passing the COUNT parameter, it will list approximately 10 keys.
Hint, or requirement
Note that the COUNT parameter can return more or less keys than specified. The COUNT is merely a recommendation for Redis and it can return back different amount of elements that you wanted it to, but it tries to be very close to the specified value.
Getting Value for a Hash Field (HGET)
The command HGET can be used to get a value for the given field. Learn more
Time Complexity: O(1)
Example usage:
Removing a Hash Field (HDEL)
The command HDEL can be used to remove a field from the hash. Learn more
Time Complexity: O(1) for single field removal, O(N) if there are multiple fields where N denotes the amount of fields.
Example usage:
Verifying the type and object encoding
To verify that the created key is a hashmap and to determine it's object encoding, we can use the basic TYPE and OBJECT ENCODING commands:
Example usage:
Removing the Hash
To finally remove the whole hash (key), the normal DEL command can be used. Learn more
Time Complexity: O(1) for removing a hash.
Usage Example of Hashes
In an example where you would have an online store where products are stored, you could have hash created for each product. For example: