【问题标题】:What is the best way to transfer the nested JSON data of a HTTP response into a SQL database?将 HTTP 响应的嵌套 JSON 数据传输到 SQL 数据库的最佳方法是什么?
【发布时间】:2021-03-27 10:31:09
【问题描述】:

我正在使用 Node.js、Fastify 和 Postgresql 创建一个 API,这应该从尚未开发的 React 客户端获取表单的数据,我想象最终将到达我的 API 的数据结构如下:

{
"quote": {
"body": "Of our qualities, none can be ascribed to the divine being without tainting it with its imperfection.",
"author": "michel de montaigne",
"page": "55",
"book": {
"title": "Diary of the Journey to Italy",
"publisher": "Eichborn Verlag",
"year": "2009"
        }
    },
"hashtag": "#God",
"user": {
"name": "betonhead",
"email": "bier@wurst.de"
    }
}

现在我想将这些值存储在我的 Postgresql 数据库中,为此我需要将数据拆分到彼此相关的不同表(作者、引用、书籍、用户等)中。

在研究如何实现我想用作 API 文件输入的 JSON 数据时,我发现了两个概念:

1. creating a view in Postgres, splitting the data via Node.js middleware.

2. store the raw JSON files directly in Postgres and from there distribute them to the tables using a function.

我现在的问题是这里哪种方法更可取,或者是否还有其他更好的方法?

感谢您的帮助。

【问题讨论】:

    标签: node.js json postgresql http fastify


    【解决方案1】:

    “最佳方式”取决于特定场景的特定约束/要求。但是,鉴于此; a) PostgreSQL 用于存储“规范化[1]”数据,b) JSON 有效负载中表示的数据与多个实体相关,c) 您预计数据的形状/结构不会经常变化,并且 d)当前的 API 调用可以充分地产生将 JSON 反序列化为适当的中间对象/实体以持久化它们的开销,然后我建议在应用程序层中执行这项工作——将实体相应地保存在它们的规范化表示中。但是,如果更需要更低的延迟,而不是避免最终的一致性[2] 问题,您可以选择将有效负载转储到一些中间持久存储(如消息队列)以供将来处理到 PostgreSQL 中的方法。

    另一种选择是使用像 MongoDB 这样的文档数据库。

    NB:如果您希望负载频繁更改和/或特定字段的形状是动态/不确定的,那么jsonb[3] 可能是一个选项。 jsonb 以二进制格式索引和存储数据,以及相关的元数据以及每个记录。 不要认为这将是这种情况下的最佳方法,但值得一提。

    更多阅读:

    1. https://en.wikipedia.org/wiki/Database_normalization
    2. https://en.wikipedia.org/wiki/Eventual_consistency
    3. Explanation of JSONB introduced by PostgreSQL
    4. https://en.wikipedia.org/wiki/CAP_theorem

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2014-11-12
      • 2011-11-09
      • 2015-02-18
      • 2013-09-15
      • 1970-01-01
      相关资源
      最近更新 更多