In our previous blogs, we discussed the basic data types available in Valkey/Redis: Strings, Lists, Sets, and Sorted Sets. In this blog, we introduce a more complex data type, Hashes.

You can think of these much like dictionaries from Python, associative arrays from PHP, etc. Normally in Valkey/Redis, you store one value associated with one key. Using a Hash, you can store several properties in a single key and manipulate each entry of the Hash.

To serialize, or not to serialize

In most programming languages, when you want to store a complex data structure to a persistent storage location, you typically need to serialize the object. Serializing is the act of turning that in-memory data structure into something that can be written to a file. Deserializing takes that on-disk representation and turns it back into the language object.

Typically, though, most applications will store this serialized representation in a database like MySQL or PostgreSQL. The downside to this approach is that you cannot manipulate the individual parts of the object while it is stored in the database. You must first fetch the entire row, deserialize it, change a field-value, then re-serialize it, and re-store it. (Note: Serializing to JSON does allow for SQL manipulation, but this may require additional code to support custom classes vs. the language’s native serializer.)

Can we do better? Sure. Let’s use Valkey/Redis and a Hash.

Hash to the rescue

We can store the same book into Valkey using a Hash datatype:

The return value of ‘3’ indicated three items were added to the single hash, ‘mybook’. We can fetch individual fields or all fields:

We can add additional fields and increment specific fields:

There are additional functions for checking if fields exist (HEXISTS), deleting fields (HDEL), setting a field if it does not already exist (HSETNX), and many others. Let’s do a quick example in Python:

Two things to note above: 1. The Valkey/Redis Python library cannot handle Python-native datetime objects, so the string representation was used. This could be handled more appropriately with a class object. 2. The value returned by hget is a binary string and thus needs to be cast into a proper integer type.

Conclusion

Custom classes and objects in code are extremely helpful in writing robust applications. When we need to store them and then manipulate them, a database system like Valkey/Redis has native abilities to fulfill these requirements natively using Hashes.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments