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

Lef*_*eff 2 amazon-dynamodb serverless-framework

我是 dynamodb 和 serverless 的新手,我已经阅读了复合排序键。我认为它们可以解决我的问题,但我不完全确定如何实施它们。在我的例子中,我有一个带有Post实体的表,它具有以下字段,它看起来像这样:

post_id <string> | user_id <string> | tags <string[]> | public <boolean>| other post data attributes...
Run Code Online (Sandbox Code Playgroud)

我需要做的查询是:

  1. 获取所有标记为公开的帖子
  2. 获取按标签过滤的帖子
  3. 获取按用户过滤的所有帖子,包括公开的和非公开的
  4. 获取单个帖子

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

因此,例如:

sort key: tag#public
Run Code Online (Sandbox Code Playgroud)

这是我之前设置的。

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
Run Code Online (Sandbox Code Playgroud)

Set*_*gan 6

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

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

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

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

             Partition Key            Sort Key
Post        POST#<post_id>           <timestamp>
User        USER#<user_id>           USER#<user_id>
Run Code Online (Sandbox Code Playgroud)

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

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