Hashes
Redis Hashes are maps between string fields and string values; therefore, they are the perfect data type to represent objects.
In our example, we wish to store information about various aquatic animals. Our goal is to create an object equivalent to the following JavaScript object:
const shamu = {
type: 'killer whale',
age: 5,
lastFeedDate: 'Jan 06 2018',
}
HSET
HSET key field value
Sets field in the hash stored at key
to value
. If key
does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.
HSET Example
Let's create our "shamu" object per the above object model:
redis> hset shamu type "killer whale"
(integer) 1
redis> hset shamu age 5
(integer) 1
redis> hset shamu lastFeedDate "Jan 06 2018"
(integer) 1
Read more about the HSET command in the Redis documentation.
HGET
HGET key field
Returns the value associated with field
in the hash stored at key
.
HGET Example
It's time to retrieve those values from the shamu
object we created in our Redis hash! Let's retrieve her last feed date so we know if it is time to feed her again:
redis> hget shamu lastFeedDate
"Jan 06 2018"
It looks like she will need food soon!
Read more about the HGET command in the Redis documentation.
HGETALL
HGETALL key
Returns all fields and values of the hash stored at key. In the returned value, every field name is followed by its value, so the length of the reply is twice the size of the hash.
HGETALL Example
Let's get all the values from our shamu
object.
redis> hgetall shamu
1) "type"
2) "killer whale"
3) "age"
4) "5"
5) "lastFeedDate"
6) "Jan 06 2018"
As shown, Redis returns a list of all the fields and values stored in the shamu
key.
Read more about the HGETALL command in the Redis documentation.