Hashes in Redis are a way to store associated field-value pairs under a single key, where both the field and values are strings. Redis allows for modifications to both the data structure as a whole, and also to each field in the structure. This makes it a great (and very fast) backing store for objects in an application.
Create a hash with two fields:
List out the fields and values associated with the hash:
Update the value of one of the fields:
Delete a single field from the hash:
Delete the hash:
Redis’s excellent documentation has more information about the available commands for hashes. I won’t copy/paste from there for you; instead, we’re going to have a little fun with them.
Dwemthy’s Array is a little example role playing game (RPG) written by Why the Lucky Stiff in Why’s (poignant) guide to Ruby to help explain Ruby metaprogramming. Here, we’re going to take the same RPG idea, and implement it using Redis hashes (with a little help from a Redis array).
We will create a hash for each monster in the array, looking something like this:
Here is an example dive into the depths of the array:
And here is the code as a whole, if you’d like to follow along: dwemthy.py
Firstly, when a user creates the array with the factory method provided, we’ll setup our data structures and return the new dwemthy.Array object:
The conn.hmset here creates a hash for the bad guy. Once that happens, we push the bad guy’s key into a Redis list, which is being used here as a simple queue.
When all the bad guys are set up, we then make sure the one at the head of the array is ready with the Array.next_enemy() method:
The self[“name”] on the last line is done by defining the __setitem__ and __getitem__ methods on the array object. This allows us to treat the array as mostly a python dict, and allows for easy fetching and modifying of the fields on the current bad guy:
The myriad ways Redis allows us to modify hashes enables developers to use it to solve a large set of problems. Hopefully this post has given you ideas to use in your own projects.