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
.
Here’s how you can model relational data in Redis:
HASH
for Table-like RecordsEach 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
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
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
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
Follow structured key patterns to organize data:
user:<id>
post:<id>
user:<id>:posts
group:<id>:users
If you're doing heavy relational modeling, consider:
Relational Concept | Redis Equivalent |
---|---|
Table | Hashes + Key patterns |
Row | A Redis hash |
Foreign Key | Manual SET/SADD links |
Join | Manual lookups |
Index | Manual 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.