首页 > 解决方案 > dynamodb 如何在 serverless.yml 中定义无键模式?

问题描述

我尝试在我的无服务器 aws lambda 中应用 dynamodb。我的文件是这样的:

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

我尝试应用 lat 和 lng 作为 storeTable 的属性,只是属性不是 key Schema,但每个 store 元素都应该具有这些属性。

但是有错误:

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

如何使 lat 和 lng 只是桅杆属性,而不是索引的关键元素?

标签: amazon-dynamodbserverless-frameworkserverless

解决方案


DynamoDB 要求您仅声明构成密钥架构的属性。(请参阅 AWS 文档

如果id是用于组成密钥架构的唯一属性,则您的资源应如下所示:

resources:
  Resources:
    StoreDynamoDbTable:
      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.TableStore}

DynamoDB 不关心其他属性。插入数据后,DynamoDB 将检测新属性,而无需在模式中声明它们。这就是非关系数据库的全部意义所在。


此外,如果您想在键模式中使用日期作为排序键,则可以使用以下内容:

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

键模式始终至少有一个分区 ( HASH) 键,并且可以选择有一个排序 ( RANGE) 键。检查此内容以了解有关 DynamoDB 的密钥架构的更多信息。


推荐阅读