dynamodb 如何在 serverless.yml 中定义无键模式?

use*_*909 2 amazon-dynamodb serverless-framework serverless

我尝试在我的无服务器 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}
Run Code Online (Sandbox Code Playgroud)

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

但是有错误:

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

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

Que*_*yot 5

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

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

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