5
votes

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

Error when I deploy

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

1
If I add manually the secondary index in the console with the sort key, it works. So I guess I wrote something wrongCecile

1 Answers

11
votes

Apparently the right syntax is this.

These were the errors:

  • You cannot add the ttl column to AttributeDefinitions (otherwise you get the error of the question)
  • You must have the columns you need for the global secondary index in the attribute definitions (otherwise you get the exact same error)
  • You must not have extra columns (message) in the attribute definitions (all give the exact same error message)
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