带有排序键的无服务器框架Dynamo DB表资源定义

时间:2017-11-20 04:40:00

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

我目前在我的serverless.yml中有一些代码。

resources:
  Resources:
    uploadBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:service}-${self:custom.stage}-uploads
    visitsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.visitsTable}
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: visitId
            AttributeType: S
          - AttributeName: comments
            AttributeType: S
          - AttributeName: attachments
            AttributeType: S
          - AttributeName: ph
            AttributeType: N
          - AttributeName: ch
            AttributeType: N
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: visitId
            KeyType: HASH
        ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5

我的目标是创建一个包含主键userId,排序键visitId的表格,并提供评论,附件,ph& CH。当我尝试sls deploy时,我收到以下错误。

无服务器错误---------------------------------------

发生错误:visitsTable - 属性AttributeDefinitions与表和二级索引的KeySchema不一致。

我在这里做错了什么?

编辑:我尝试过的另一次尝试

resources:
  Resources:
    uploadBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:service}-${self:custom.stage}-uploads
    visitsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.visitsTable}
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: visitId
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: visitId
            KeyType: RANGE
        ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5

1 个答案:

答案 0 :(得分:11)

AWS DynamoDb是一个NO-SQL类型的数据库,无需在创建表时定义所有键。同样从AWS文档中可以清楚地看出,在属性定义中,您必须指定密钥架构和索引。

  

描述表和索引的键架构的属性数组。

请编辑您的代码,如下所示

resources:
  Resources:
    uploadBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:service}-${self:custom.stage}-uploads
    visitsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.visitsTable}
        AttributeDefinitions:
          - AttributeName: userId
            AttributeType: S
          - AttributeName: visitId
            AttributeType: S
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: visitId
            KeyType: RANGE
        ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5

更多CreateTable