【问题标题】:How to implement Twitter tweet, reply and retweet database schema without empty columns/cells如何在没有空列/单元格的情况下实现 Twitter 推文、回复和转发数据库架构
【发布时间】:2020-11-01 21:18:38
【问题描述】:

您将如何以尽可能最好和最高性能的方式为类似 twitter 的应用程序设计数据库?

在这个应用程序中,用户可以发推文、回复和转发。推文、回复和转发最终会创建一条新推文。所以我们可以很容易地创建这样的模式:

tweets
  - id - integer
  - text - string -> this is non nullable
  - userId - integer
  - createdAt - date
  - parentId - integer -> when replying, this will be the parent tweet of the reply
  - isRetweet - boolean -> this becomes true only when the current tweet is a retweet. The parentId will have the id of the tweet that was retweeted

但是让我们介绍另一个功能:用户可以在不写text 的情况下转发推文(这是 Twitter 目前的工作方式)。在这种情况下,我们必须使我们的text 列可以为空。突然之间,这意味着我们可以在没有 text 的情况下创建推文和回复,因为不再有关于此的数据库限制(现在让我们忽略应用层验证)。

我的方法是为此再创建 3 个表。最后我们将有 4 个表:

tweets
  - id - integer
  - text - string
  - userId - integer
  - createdAt - date

replies
  - tweetId - integer -> this will contain the content of the reply
  - parentId - integer -> this is the parent of the reply

retweetsWithText
  - tweetId - integer -> this will contain the content of the retweet
  - parentId - integer -> this is the parent of the retweet

retweetsWithoutText
  - tweetId - integer -> this will contain the reference for the retweeted tweet
  - userId - integer -> who retweeted the tweet. We need this because we won't save anything in the `tweets` table regarding retweets without text
  - createdAt - date

我知道这可能查询起来很复杂,但最后我认为这将在存储方面带来最佳性能(不需要 parentId 和 isRetweet)。这也将解决没有文字转推的问题。第一种方法的另一个问题是 parentId 很可能为 null,因为根据统计数据,只有 30% 的推文得到评论或转发。所以我们最终会得到很多用于 parentId 的 NULL 列

有没有更简单的方法来解决这个问题,表格更少,最好没有空/冗余单元格?

【问题讨论】:

    标签: database twitter relational-database database-schema


    【解决方案1】:

    在您的最后一个具有多个表的架构中:您计划如何在不查询多个表的情况下查询用户的时间线,然后合并结果,并最终将然后合并的结果切片以允许分页?

    也就是说,即使依赖NULL的方式可能会导致磁盘空间被占用,查询起来也更快。

    在数据库模式设计中,总是需要在插入速度和查询速度之间进行权衡。对于类似 twitter 的应用程序,查询速度胜出(在 OLTP 工作负载中大多数时间都是这种情况)。

    您需要对这两种解决方案进行基准测试,并添加第三个选项,如果您使用 PostgreSQL,则依赖表继承。

    提示:我对 PostgreSQL 文件序列化不太了解,但如果它类似于 FoundationDB 元组模块,则在一行的列中编码 NULL 值只需 1 个字节。

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      相关资源
      最近更新 更多