【问题标题】:How to define DynamoDB table with global secondary index in serverless framework如何在无服务器框架中使用全局二级索引定义 DynamoDB 表
【发布时间】:2019-12-10 20:31:37
【问题描述】:

我的 DynamoDB 表

  • awsRequestID (S)
  • ttl (N)
  • 创建日期 (S) (ISO)
  • user_id (S)
  • 消息(S)

我想达到的目标

我想要一个全局二级索引,这样我就可以查询以过滤用户的所有消息,并按照https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html 中的说明对它们进行排序(使用排序键)

serverless.yml

resources:
  Resources:
    EventsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.eventsTable}
        AttributeDefinitions:
          - AttributeName: awsRequestID
            AttributeType: S
          - AttributeName: ttl
            AttributeType: N
          - AttributeName: createdate
            AttributeType: S
          - AttributeName: user_id
            AttributeType: S
          - AttributeName: message
            AttributeType: S
        KeySchema:
          - AttributeName: awsRequestID
            KeyType: HASH
        GlobalSecondaryIndexes:
          - IndexName: UserIdIndex
            KeySchema:
              - AttributeName: user_id
                KeyType: HASH
              - AttributeName: createdate
                KeyType: RANGE
            Projection:
              ProjectionType: 'ALL'
        TimeToLiveSpecification:
          AttributeName: ttl
          Enabled: true
        BillingMode: PAY_PER_REQUEST

部署时出错

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

【问题讨论】:

  • 如果我使用排序键在控制台中手动添加二级索引,它可以工作。所以我想我写错了

标签: amazon-dynamodb serverless-framework


【解决方案1】:

显然正确的语法是这样的。

这些是错误:

  • 不能将 ttl 列添加到 AttributeDefinitions(否则会出现问题的错误)
  • 属性定义中必须包含全局二级索引所需的列(否则会出现完全相同的错误)
  • 属性定义中不能有额外的列(消息)(都给出完全相同的错误消息)
resources:
  Resources:
    EventsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.eventsTable}
        AttributeDefinitions:
          - AttributeName: awsRequestID
            AttributeType: S
          - AttributeName: user_id
            AttributeType: S
          - AttributeName: createdate
            AttributeType: S
        KeySchema:
          - AttributeName: awsRequestID
            KeyType: HASH
        GlobalSecondaryIndexes:
          - IndexName: UserIdIndex
            KeySchema:
              - AttributeName: user_id
                KeyType: HASH
              - AttributeName: createdate
                KeyType: RANGE
            Projection:
              ProjectionType: 'ALL'
        TimeToLiveSpecification:
          AttributeName: ttl
          Enabled: true
        BillingMode: PAY_PER_REQUEST

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2016-10-28
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多