gpt4 book ai didi

many-to-many - 如何在redis中建立多对多关系

转载 作者:IT王子 更新时间:2023-10-29 05:54:56 28 4
gpt4 key购买 nike

在关系数据库中,我有一个用户表、一个类别表和一个执行多对多关系的用户类别表。

这个结构在Redis中是什么形式的?

最佳答案

对于 Redis,关系通常由集合表示。一套可以用表示单向关系,因此每个对象需要一组表示多对多关系。

尝试将关系数据库模型与 Redis 进行比较是毫无用处的数据结构。使用 Redis,一切都以非规范化的方式存储。示例:

# Here are my categories
> hset category:1 name cinema ... more fields ...
> hset category:2 name music ... more fields ...
> hset category:3 name sports ... more fields ...
> hset category:4 name nature ... more fields ...

# Here are my users
> hset user:1 name Jack ... more fields ...
> hset user:2 name John ... more fields ...
> hset user:3 name Julia ... more fields ...

# Let's establish the many-to-many relationship
# Jack likes cinema and sports
# John likes music and nature
# Julia likes cinema, music and nature

# For each category, we keep a set of reference on the users
> sadd category:1:users 1 3
> sadd category:2:users 2 3
> sadd category:3:users 1
> sadd category:4:users 2 3

# For each user, we keep a set of reference on the categories
> sadd user:1:categories 1 3
> sadd user:2:categories 2 4
> sadd user:3:categories 1 2 4

一旦我们有了这个数据结构,就可以很容易地使用集合代数查询它:

# Categories of Julia
> smembers user:3:categories
1) "1"
2) "2"
3) "4"

# Users interested by music
> smembers category:2:users
1) "2"
2) "3"

# Users interested by both music and cinema
> sinter category:1:users category:2:users
1) "3"

关于many-to-many - 如何在redis中建立多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907942/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com