【问题标题】:how to have relations many to many in redis如何在redis中建立多对多关系
【发布时间】:2012-06-10 02:21:52
【问题描述】:

在关系数据库中,我有一个用户表、一个类别表和一个用户类别表,它们之间存在多对多关系。

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

【问题讨论】:

    标签: many-to-many redis


    【解决方案1】:

    使用 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"
    

    【讨论】:

    • 谢谢!我是 Redis 新手,这很有趣 :)
    • 我们如何获得类别 smembers category:2:users 的名称,因为它给出了类别编号
    • 多年后这仍然是推荐的方法吗?
    • @Didier Spezia - 请您在这里帮助我们stackoverflow.com/questions/53265496/…
    【解决方案2】:

    恕我直言,Redis 不是用于进行结构化查询 (SQL),而是用于快速访问数据,您可以这样做: 例如,以 user_id 为键创建一个“表”,数据是一个包含朋友的列表。然后您查询 user_id 并处理您需要的内容。这与标准化相反。如果数据的顺序很重要,例如状态更新,您所做的就是将数据推送和弹出到列表中。例如,表“status”以 user_id 作为键,数据是一个列表。例如,您 lpush 数据,然后查询最后 20 个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多