How to Use Redis Hashes for Storing Object-like Items
In previous articles, we learned about using Lists and Sets to associate a key with a single value or a group of values. However, there are cases where we need to associate multiple values with a single key, such as when storing object-like items. This is where Redis Hashes come in handy.
Let’s take an example of a person who has a name and an age. We can create a Redis Hash called person:1
and associate the name and age with it using the HMSET
command:
1 | HMSET person:1 name "Flavio" age 37 |
To retrieve all the properties of a user from the Redis Hash, we can use the HGETALL
command:
1 | HGETALL person:1 |
This will return all the properties of the person as key-value pairs.
If we want to update a specific property of the person, we can use the HSET
command:
1 | HSET person:1 age 38 |
By specifying the key and the new value, we can easily update the value of a specific property in the Redis Hash.
Furthermore, if we want to increment a value stored in the Redis Hash, we can use the HINCRBY
command:
1 | HINCRBY person:1 age 2 |
This command will increment the age value by the specified amount.
Redis provides a variety of hash commands that can be used to manipulate and perform operations on hashes. You can find a complete list of hash commands in the Redis documentation here.
Using Redis Hashes can be a powerful way to store and retrieve object-like data with ease. It allows for efficient storage and retrieval of multiple values associated with a single key.
Tags: Redis, Hashes, Redis commands