dynamodb how to define none key schema in serverless.yml?

Viewed 1933

I try to apply a dynamodb in my serverless aws lambda. My file is like:

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}

I try to apply lat and lng as attributes of storeTable, just the attribute not key Schema, but every store element should have these attributes.

But there is error:

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

How to make lat and lng just mast attribute,not key element for index?

1 Answers

DynamoDB requires that you declare ONLY the attributes that compose your key schema. (See AWS docs)

If id is the only attribute that is used to compose your key schema, your resource should look like this:

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 doesn't care about the other attributes. Upon inserting your data, DynamoDB will detect the new attributes without having to declare them in a schema. That's the whole point of a non-relational database.


Additionally, if you wanted to have a date as sort key in your key schema, you could have something like this:

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}

A key schema always have at least a partition (HASH) key and can optionally have a sort (RANGE) key. Check this to learn more about DynamoDB's key schema.

Related