user
How to create relational tables with REDIS?
alphonsio

Redis is not a relational database, so it doesn't natively support relational tables like SQL databases do (e.g., tables with foreign keys, joins, schemas, etc.). However, you can simulate relational tables using Redis data structures like HASH, SET, LIST, and ZSET.


Simulating Relational Tables in Redis

Here’s how you can model relational data in Redis:


1. Use HASH for Table-like Records

Each record is stored as a Redis hash, similar to a row in a SQL table.

Example: "Users" table

HMSET user:1 id 1 name "Alice" email "alice@example.com"
HMSET user:2 id 2 name "Bob" email "bob@example.com"

You can get the user:

HGETALL user:1

2. Simulate Relationships

a. One-to-Many Relationship

Example: Each user has multiple posts.

# Posts (like a separate "table")
HMSET post:1 id 1 user_id 1 title "Hello"
HMSET post:2 id 2 user_id 1 title "Redis Tips"

# Index: Link user to their posts
SADD user:1:posts 1 2

To get all posts by user 1:

SMEMBERS user:1:posts
HGETALL post:1
HGETALL post:2

b. Many-to-Many Relationship

Example: Users and Groups.

# Add user to groups
SADD user:1:groups group:1 group:2
SADD user:2:groups group:1

# Add group to users
SADD group:1:users user:1 user:2
SADD group:2:users user:1

To find all users in group 1:

SMEMBERS group:1:users

3. Indexes and Queries (manually maintained)

Redis doesn’t auto-index. If you want to find users by email, you create a reverse index:

SET user:by_email:alice@example.com user:1
GET user:by_email:alice@example.com
HGETALL user:1

Tip: Use a Key Naming Convention

Follow structured key patterns to organize data:

  • user:<id>
  • post:<id>
  • user:<id>:posts
  • group:<id>:users

Optional Tools for Relational-like Abstraction

If you're doing heavy relational modeling, consider:

  • RediSQL – SQL engine on top of Redis
  • Redis OM – Object Mapping layer (available for Python, Node.js, .NET)
  • RedisJSON – Store JSON documents for more flexible schemas

Summary

Relational ConceptRedis Equivalent
TableHashes + Key patterns
RowA Redis hash
Foreign KeyManual SET/SADD links
JoinManual lookups
IndexManual reverse index

Redis can model relational-like data efficiently if relationships are simple and well structured, but for complex joins or dynamic queries, a traditional relational DB is better.