【问题标题】:How can I define a composite key in serverless.yml for DynamoDB?如何在 serverless.yml 中为 DynamoDB 定义复合键?
【发布时间】:2017-10-22 11:30:59
【问题描述】:

我正在尝试定义一个具有 3 列复合键的 dynamodb 表。这可能吗?

我见过有这样代码的示例和教程:

resources:
  Resources:
    TodosDynamoDbTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

但这只有一列和一个键。我的桌子是这样的:

  Properties:
    AttributeDefinitions:
      - AttributeName: id
        AttributeType: N
      - AttributeName: server
        AttributeType: S
      - AttributeName: room
        AttributeType: S
      - AttributeName: friendlyName
        AttributeType: S

我想要idserverroom 上的密钥。用户可以在同一台服务器上的多个房间中,也可以在多台服务器上的多个房间中。但是,在这三个键中,它始终是唯一的。

我不知道如何定义KeySchema 部分。有什么帮助吗?

【问题讨论】:

    标签: amazon-web-services amazon-dynamodb serverless-framework


    【解决方案1】:

    首先,您不能在 DynamoDB 中创建复合键(如在关系数据库中)。

    您在表中获得的键是 Hash 和 Range(也称为排序和可选)键。由于这限制了查询能力,DynamoDB 支持创建称为全局二级索引(GSI)和本地二级索引(LSI)的索引来扩展查询能力。

    根据您的架构,由于 id、server 和 room 的组合是唯一的,您可以对 Hash 键使用串联,例如 id_server_room,以便强制执行表中的项目以实现唯一性。

    然后您可以创建 id、server 和 room 作为属性。要有效地从这些属性中进行查询,请根据需要创建 GSI。

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2017-11-30
      • 2021-02-23
      • 2012-05-13
      • 2010-11-09
      • 1970-01-01
      • 2018-04-29
      • 2017-08-01
      • 2023-01-19
      相关资源
      最近更新 更多