亚马逊 DynamoDB 单个 table;在单个请求中获取帖子和用户信息

Amazon DynamoDB single table; Get posts and users info in a single request

我正在为数据库使用 Amazon DynamoDB,并希望采用单一 table 设计。

我的数据类型是用户、帖子、类别、评论等。我可以获得 posts 列表,但我需要为每个 [=] 获取 posts 和用户(作者)数据54=](例如名字、姓氏等)

预计访问模式如下:

通过 ID 获取用户(完成)

我正在使用 Dynamoose:

const dynamoose = require("dynamoose");
const { Schema } = dynamoose;
   
const ServiceSchema = new Schema({
  pk: {
    type: String,
    hashKey: true,
  },
  sk: {
    type: String,
    rangeKey: true,
  },
  id: {
    type: String,
  },
  createdAt: {
    type: Date,
    default: new Date(),
    index: {
      global: true,
      name: "createdAtIndex",
    },
  },
  updatedAt: {
    type: Date,
    default: new Date(),
    index: {
      global: true,
      name: "updatedAtIndex",
    },
  },
  deleted: {
    type: Boolean,
    default: false,
  },
  firstName: {
    type: String,
  },
  lastName: {
    type: String,
  },
  username: {
    type: String,
    index: {
      global: true,
      name: "usernameIndex",
    },
  },
  userStatus: {
    type: String,
    enum: ["pending", "active"],
    index: {
      global: true,
      name: "userStatusIndex",
    },
  },
  categories: {
    type: Array,
    schema: [String],
  },
  title: String,
  body: String,
  publishStatus: {
    type: String,
    enum: ["pending", "published"],
    index: {
      global: true,
      name: "publishStatusIndex",
    },
  },

});

module.exports = dynamoose.model("service", ServiceSchema, {
  create: true,
});

数据(更新:我决定更换pk和sk: 所以现在PK是USER#1234,SK是POST#5678):

我需要的响应 post 是这样的:

{
  id: '1234',
  title: 'Test',
  body: 'This is body',
  user: {
    id: '5678',
    firstName: 'David',
    picture: 'myImage.jpg',
    points: 12 // **This is very important. And it's the main issue. I need to change this value every day.**
  },
  categories: [
    { "id": "cat1", "name": "Sport" },
    { "id": "cat2", "name": "Cinema" }
  ]
}

更新 1: 这是社交网络的原型。

更新 2: 我正在使用 GraphQL。我还决定更换 pk 和 sk: 所以现在PK是USER#1234,SK是POST#5678.

NoSQL 数据库通常会要求您对数据进行反规范化以满足应用程序的访问模式。换句话说,如果你想要这样的回应:

{
  id: '1234',
  title: 'Test',
  body: 'This is body',
  user: {
    id: '5678',
    firstName: 'David',
    picture: 'myImage.jpg'
  },
  categories: [
    { "id": "cat1", "name": "Sport" },
    { "id": "cat2", "name": "Cinema" }
  ]
}

您需要将所有这些信息存储在同一个分区中。

我可以从您的屏幕截图中看到您将用户 ID 与 post 一起存储。但是,您没有将所需的用户信息与 post(例如名字和图片)一起存储。要解决您的问题,您可以考虑以下几种方法:

  1. 每个 post 存储用户的名字和照片。如果你有可变的属性(随时间变化——比如用户图片),这可能会很棘手。在处理可变数据时,您可能需要考虑第二种选择。
  2. 将获取 post 分为两个步骤:1) 获取 post,然后 2) 获取用户详细信息(均在服务器端)。这意味着您要往返 DDB 两次,但这在您的应用程序中可能是可以接受的权衡。
  3. 发挥创意!您可以将用户个人资料图片存储在安全的 S3 存储桶中。也许用户个人资料图片的键可以包含关于用户的不可变信息(例如用户 ID,永远不会改变的东西)。这样,用户可以随心所欲地更新他们的个人资料图片。您的应用程序会知道 ID 为 1234 的用户始终在标记为 /your-app/user/1234-profile.jpg(例如)
  4. 的 S3 存储桶中拥有他们的最新个人资料照片