Learn Redis · 3/15

Data Modeling Basics: Organizing Data with Hashes

6 min read

Data Modeling Basics: Organizing Data with Hashes 🗂️

Welcome back! So far, you've seen how Redis can handle simple key-value pairs where the value is just a single string. But what if you need to store something more structured, like a user's profile with their name, email, and age? You could jam it all into a JSON string, but that's like putting all your different spices into one big jar. It works, but it's not very efficient if you only need a pinch of paprika. This is where Redis Hashes come to the rescue!

1. Introduction to Hashes: Storing Objects in Redis 🧍

The Problem: Imagine you're building a system to manage user profiles. Each user has multiple attributes: a username, an email address, and maybe a score. With simple strings, you might end up with keys like user:101:username, user:101:email, and user:101:score. This approach can get messy and inefficient, especially when you have millions of users. Every single key in Redis has some memory overhead associated with it.

The Solution: Redis Hashes are the perfect data structure for this job. A Hash is a collection of field-value pairs stored at a single key. Think of it as a mini key-value store within a larger one, much like a dictionary in Python or an object in JavaScript. This allows you to group all the related information about an object, like a user, under a single key.

Using a Hash, our user profile example becomes much cleaner. We'd have a single key, say user:101, and within that Hash, we'd have fields for "username," "email," and "score." This approach is not only more organized but also more memory-efficient, especially for smaller objects.

Under the Hood: For small hashes, Redis uses a special memory-optimized encoding called a "ziplist". This stores the hash's fields and values in a contiguous block of memory, which significantly reduces the memory footprint compared to storing each piece of data as a separate key. Once the hash grows beyond a certain size or number of entries, Redis transparently converts it to a more standard hash table to maintain fast lookup times.


2. Setting and Retrieving Hash Fields: HSET and HGET 🛠️

Now that we understand what Hashes are, let's see how to work with them. The two most fundamental commands are HSET for setting data and HGET for retrieving it.

HSET: Setting a Field's Value

The HSET command allows you to set the value of a specific field within a hash. If the hash or the field doesn't exist, HSET will create them for you. If the field already exists, its value will be updated.

Syntax:
HSET key field value [field value ...]

Example:
Let's create a profile for a user with the ID 123.

bash
HSET user:123 username "coder_cat"
# (integer) 1  -> This means 1 new field was created.

HSET user:123 email "[email protected]"
# (integer) 1

HSET user:123 username "super_coder_cat"
# (integer) 0 -> This means an existing field was updated.

HGET: Retrieving a Field's Value

To get the value of a single field from a hash, you use the HGET command.

Syntax:
HGET key field

Example:
Let's retrieve the username and email for our user.

bash
HGET user:123 username
# "super_coder_cat"

HGET user:123 email
# "[email protected]"

HGET user:123 non_existent_field
# (nil) -> Returns nil if the field doesn't exist.

Industry Practice: It's a common convention to name your keys with a prefix followed by a colon, like user:123, to create a sort of namespace for your data. This helps in organizing and managing your keys.


3. Managing Multiple Fields: HMSET and HGETALL 🗂️➡️📦

Making multiple trips to the store for individual ingredients is inefficient. Similarly, setting or getting hash fields one by one can be slow. Redis provides commands to handle multiple fields at once.

HMSET (Deprecated) and the modern HSET:

The HMSET command was used to set multiple field-value pairs in a single operation. However, as of Redis 4.0.0, HMSET is considered deprecated. The good news is that HSET was updated to handle multiple field-value pairs, making it the one-stop-shop for setting hash data.

Syntax (HSET with multiple fields):
HSET key field1 value1 field2 value2 ...

Example:
Let's create a new user profile for user 456 in one go.

bash
HSET user:456 name "dev_dog" email "[email protected]" plan "premium"
# (integer) 3 -> Indicates that 3 new fields were created.

HGETALL: Getting All Fields and Values

To retrieve all the fields and their corresponding values from a hash, you can use the HGETALL command. This command returns a list of alternating fields and values.

Syntax:
HGETALL key

Example:
Let's get the entire profile for user 456.

bash
HGETALL user:456
# 1) "name"
# 2) "dev_dog"
# 3) "email"
# 4) "[email protected]"
# 5) "plan"
# 6) "premium"

⚠️ A Word of Caution: Be mindful when using HGETALL on very large hashes. Since it retrieves all the data in the hash, it can be a slow operation and might block other operations on your Redis server. For large hashes, consider if you truly need all the fields or if you can retrieve just the ones you need with HMGET (which gets multiple specified fields).


4. Incrementing Values Inside Hashes 📈

Imagine you're keeping track of a user's score in a game or the number of times a product has been viewed. You'll frequently need to increment a numeric value. While you could HGET the value, increment it in your application, and then HSET it back, this is inefficient and can lead to race conditions in a multi-user environment.

The Atomic Solution: HINCRBY

Redis provides the HINCRBY command to atomically increment an integer value stored in a hash field. If the field doesn't exist, it's created with a value of 0 before the increment is applied.

Syntax:
HINCRBY key field increment

Example:
Let's create a stats hash for a blog post and track its views.

bash
HSET post:789 title "Learning Redis" views 100
# (integer) 2

# Let's increment the views by 1
HINCRBY post:789 views 1
# (integer) 101

# We can also increment by a larger number
HINCRBY post:789 views 10
# (integer) 111

# And yes, you can decrement by using a negative number!
HINCRBY post:789 views -5
# (integer) 106

# What if we want to track likes and the field doesn't exist yet?
HINCRBY post:789 likes 1
# (integer) 1 -> The 'likes' field was created and set to 1.

This atomic operation is incredibly fast and ensures that your counters are always accurate, even with many concurrent updates.

Further Reading 📚

Challenge

You are the backend developer for a new online multiplayer game. Your task is to manage player inventory and stats using Redis Hashes. Write the sequence of Redis commands required to perform the following operations for a player with the key player:101.

  1. A new player, player:101, has just registered. Using a single command, set their profile with the username "RogueOne", class "Thief", and an initial gold count of 500.
  2. The player completed a quest. Atomically increment their xp (experience points) by 150.
  3. As part of the same quest reward, their gold count also needs to be increased. Atomically increment their gold by 250.
  4. The player has equipped a new item. Add a new field weapon with the value "Shadow Blade" to their hash.
  5. For a party UI display, you need to fetch only the username and xp for player:101.
  6. The player bought an item from the in-game store, costing 75 gold. Atomically decrement their gold count by this amount.
  7. To generate a full player profile view, retrieve all fields and values associated with player:101.

Expected result

Your solution should be a sequence of Redis commands that correctly perform all the requested operations in order.

redis
HSET player:101 username "RogueOne" class "Thief" gold 500
HINCRBY player:101 xp 150
HINCRBY player:101 gold 250
HSET player:101 weapon "Shadow Blade"
HMGET player:101 username xp
HINCRBY player:101 gold -75
HGETALL player:101
redis

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.