目前,在我的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

最佳答案

AWS DynamoDb是一个NO-SQL类型的数据库,无需在创建表期间定义所有键。从AWS文档中还可以清楚地看到,在Attribute Definition中,您必须指定Key模式和索引。


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


请按以下方式编辑您的代码

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

09-04 22:10
查看更多