1

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

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

访问模式预计如下:

通过 ID 获取用户(完成)

  • 获取所有用户(完成userStatusIndex
  • 按类别 ID 获取所有帖子(完成)
  • 获取用户的所有帖子:我可以获取帖子列表,publishStatusIndex但我也需要作者信息和类别详细信息。(每个帖子的作者信息和类别详细信息)
  • 获取所有用户的所有帖子:(以上案例)

我正在使用 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:所以现在 PKUSER#1234和 SK 是POST#5678): 在此处输入图像描述

我需要的回复帖子是这样的:

{
  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

4

1 回答 1

2

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 与帖子一起存储。但是,您不会将所需的用户信息与帖子一起存储(例如名字和图片)。要解决您的问题,您可以考虑以下几种方法:

  1. 在每个帖子中存储用户的名字和图片。如果您的属性是可变的(随时间变化 - 就像用户图片),这可能会很棘手。在处理可变数据时,您可能需要考虑第二种选择。
  2. 将获取帖子分为两步:1) 获取帖子然后 2) 获取用户详细信息(都在服务器端)。这意味着您需要两次往返 DDB,但这可能是您的应用程序中可接受的折衷方案。
  3. 发挥创意!您可以将用户个人资料图片存储在安全的 S3 存储桶中。也许用户头像的关键字可以包括关于用户的不可变信息(例如,用户 ID,永远不会改变的东西)。这样,用户可以根据需要更新他们的个人资料图片。您的应用程序会知道 ID 为 1234 的用户在 S3 存储桶中始终具有他们最新的个人资料图片,标记为/your-app/user/1234-profile.jpg(例如)
于 2021-09-27T18:19:05.033 回答