0
0
Redisquery~5 mins

Embedding vs referencing in Redis

Choose your learning style9 modes available
Introduction

Embedding and referencing are two ways to store related data in Redis. They help organize data for easy access and updates.

When you want to store all related information together for quick access.
When data is small and changes together, embedding is easier.
When data is large or shared across many places, referencing avoids duplication.
When you want to update parts of data independently.
When you want to keep your data organized and avoid repeating the same info.
Syntax
Redis
Embedding: Store related data inside one Redis key, often as a hash or JSON string.
Referencing: Store related data in separate keys and link them using IDs or keys.

Embedding keeps data together, so you get everything with one read.

Referencing stores data separately, so you can update parts without touching others.

Examples
This example embeds user details in one hash key.
Redis
HSET user:1000 name "Alice" age 30 address "123 Main St"
This example references the address separately by storing it in another key.
Redis
HSET user:1000 name "Alice" age 30
SET address:1000 "123 Main St"
Sample Program

This shows embedding user info in one hash and referencing address in another. You get user data and address separately.

Redis
HSET user:1 name "Bob" age 25
HSET address:1 street "456 Oak Rd" city "Springfield"

# To get embedded data:
HGETALL user:1

# To get referenced data:
HGETALL user:1
HGETALL address:1
OutputSuccess
Important Notes

Embedding is faster for reading all data at once.

Referencing is better when parts of data change often or are shared.

Choose based on how you use and update your data.

Summary

Embedding stores related data together in one key.

Referencing stores related data in separate keys linked by IDs.

Use embedding for simple, small, and tightly connected data.