使用无服务器框架为 dynamodb 设置复合排序键

Setting composite sort keys for dynamodb with serverless framework

我是 dynamodb 和无服务器的新手,我已经阅读了 composite sort keys。我认为它们可以解决我的问题,但我不完全确定如何实施它们。在我的例子中,我有一个 table 和一个 Post 实体,它有以下字段,它看起来像这样:

post_id <string> | user_id <string> | tags <string[]> | public <boolean>| other post data attributes...

我需要做的查询是:

  1. 获取所有标记为public
  2. 的post
  3. 获取 posts 按标签筛选
  4. 获取所有 post 由用户过滤,包括 public 和不 public
  5. 获得一个post

我只能为标有 public 的实体设置 public 属性。 如何使用无服务框架定义复合排序键。

因此,例如:

sort key: tag#public

这是我之前设置的。

PostsDynamoDBTable:
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: postId
            AttributeType: S
          - AttributeName: userId
            AttributeType: S
          - AttributeName: createdAt
            AttributeType: S
        KeySchema:
          - AttributeName: postId
            KeyType: HASH
          - AttributeName: userId
            KeyType: RANGE
        BillingMode: PAY_PER_REQUEST
        TableName: ${self:provider.environment.POSTS_TABLE}
        GlobalSecondaryIndexes:
          - IndexName: ${self:provider.environment.USER_ID_INDEX}
            KeySchema:
              - AttributeName: userId
                KeyType: HASH
              - AttributeName: public
                KeyType: RANGE
            Projection:
              ProjectionType: ALL

复合排序键是指您如何使用排序键。

您在 serverless.yml 中唯一需要做的就是定义排序键名称(您已在此处完成)。是否将该排序键用作复合排序键(或不)取决于您的应用程序。您要么将排序键的值设置为复合值(例如 CA#BEVERLYHILLS#90210),要么不设置(例如 BEVERLYHILLS)。 DynamoDB 或 Serverless Framework 都不在乎,更多的是关于如何在应用程序逻辑中使用键。

请记住,DynamoDB 允许您在单个 table 中存储多个实体。这些实体可能有不同的主键(分区键和排序键)。因此,我建议您将分区键命名为 PK 并将排序键命名为 SK。

例如,假设您将 Post 和用户实体定义为具有以下主键:

             Partition Key            Sort Key
Post        POST#<post_id>           <timestamp>
User        USER#<user_id>           USER#<user_id>

在 Post 的情况下,您的排序键可以是时间戳(制作 post 的时间)。对于用户,排序键可以是用户的 ID。那么在定义 table 时如何命名排序键字段?

我喜欢将排序键命名为 SK,以提醒您正在使用该字段来组织数据。当然,您可以随意命名它,但是如果您将其命名为 userId,就像您在 serverless.yml 文件中所做的那样,您可能会忘记该字段可以包含用户以外的其他内容ID!