How to define DynamoDB table with global secondary index in serverless framework

Cec*_*ile 6 amazon-dynamodb serverless-framework

My DynamoDB table

  • awsRequestID (S)
  • ttl (N)
  • createdate (S) (ISO)
  • user_id (S)
  • message (S)

What I try to achieve

I want to have a global secondary index so I can query to filter all the messages of a users and I get them ordered (using the sort key) as explained in 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
Run Code Online (Sandbox Code Playgroud)

Error when I deploy

An error occurred: EventsTable - Property AttributeDefinitions is inconsistent with the KeySchema of the table and the secondary indexes.

Cec*_*ile 13

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

这些是错误:

  • 您不能将 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
Run Code Online (Sandbox Code Playgroud)