Search code examples
database-designnosqlamazon-dynamodb

Should non-primary-key attributes be part of a DynamoDB table definition?


I'm new to DynamoDB (and NoSQL databases in general) so this is a pretty basic question.

Am working with existing code where a DynamoDB table is created via CloudFormation with YAML similar to the following:

MyDynamoDBTable:
  Type: AWS::DynamoDB::Table
  Properties:
    TableName: MyDynamoDBTable
    AttributeDefinitions:
      - AttributeName: Id
        AttributeType: S
    KeySchema:
      - AttributeName: Id
        KeyType: HASH
    ProvisionedThroughput:
      ReadCapacityUnits: 5
      WriteCapacityUnits: 5

The above just defines an Id column and no other attributes - but then in the code, further attributes (strings named Type and Payload) are always used when adding new items.

Have previously only worked with relational databases so this paradigm of adding attributes that aren't in a schema feels a bit alien. My question is would it ever be appropriate to include other attributes in the table definition that aren't part of the primary key? E.g. adding the following attributes to the AttributeDefinitions section:

      - AttributeName: Type
        AttributeType: S
      - AttributeName: Payload
        AttributeType: S

Would it be better to do this if I know up-front that such attributes will always be present for all items? Or is it better to be minimalist and only define a primary key and nothing else to allow for complete flexibility? (But if this always the best practice, why does the table definition allow you to do otherwise?)


Solution

  • Never. There is no option to define non-key attributes as part of table definition.

    Despite its generic-sounding name, AttributeDefinitions are for Partition and Sort Key fields only*. It is "An array of attributes that describe the key schema for the table and indexes". Only the 3 key-eligible data types are permitted (String, Number, Binary) as an AttributeType. An AttributeName can be referenced in multiple KeySchema if secondary indexes are defined.

    The KeySchema Specifies the attributes that make up the primary key for a table or an index. The attributes in KeySchema must also be defined in the AttributeDefinitions array.


    * docs: The primary key that uniquely identifies each item in an Amazon DynamoDB table can be simple (a partition key only) or composite (a partition key combined with a sort key).