Redis Hash

Redis Hash

A Redis Hash is a data structure in Redis that stores a set of key-value pairs, similar to an object or map in programming languages. It is ideal for representing objects with multiple attributes, such as a user with a name, age, and email.

Each field in a hash can be accessed or modified individually, making it efficient in terms of memory and performance. With commands like HSET, HGET, and HGETALL, data can be managed quickly and easily.

Hashes are widely used to store structured data in applications.

HSET

With the HSET command, we can define a hash as follows:

hset myMedia title "Inception"
(integer) 1

After the HSET command, we must provide the parameters key, field, and value.

In the example above, we set the value Inception to the field title, which belongs to the hash myMedia.

In the example above, we defined just one key/value pair, but we could define more than one, for example:

hset myMedia title "Inception" is_popular true
(integer) 1

HGET

We use the hget command to retrieve the value of a field within a hash.

hget myMedia title
"Inception"

HGETALL

We can retrieve the value of all fields in a hash with the hgetall command.

hgetall myMedia
1) "title"
2) "Inception"
3) "is_popular"
4) "true"

HDEL

We can remove a field within a hash with the hdel command.

hdel myMedia is_popular
(integer) 1

We remove the field is_popular.

hgetall myMedia
1) "title"
2) "Inception"

HLEN

We can use the hlen command to retrieve the number of fields in a hash.

hlen myMedia
(integer) 1

Adding another field:

hset myMedia age_rating 13
(integer) 1

Retrieve the number of fields within the hash again.

hlen myMedia
(integer) 2