From the command line or the online API, I have no trouble creating a "composite primary key" but when I try to use CloudFormation to do the job for me, I don't see any JSON/YAML that will let me set something called a "composite primary key". The language is completely different so I was hoping someone could guide me as to how I create such a key using Cloudformation.
My best guess is something like the following where I want the composite key to consist of both userId and noteId:
Resources:
usersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: notes_serverless
AttributeDefinitions:
- AttributeName: userId
AttributeType: S
- AttributeName: noteId
AttributeType: S
KeySchema:
- AttributeName: userId
KeyType: HASH
- AttributeName: noteId
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
Partition key and sort key – Referred to as a composite primary key, this type of key is composed of two attributes. The first attribute is the partition key, and the second attribute is the sort key. DynamoDB uses the partition key value as input to an internal hash function.
DynamoDB supports two types of primary keys: Partition key: A simple primary key, composed of one attribute known as the partition key. Attributes in DynamoDB are similar in many ways to fields or columns in other database systems.
There are two types of primary keys in DynamoDB: Partition key: This is a simple primary key. If the table has only a partition key, then no two items can have the same partition key value. Composite primary key: This is a combination of partition key and sort key.
In contrast, DynamoDB tables are schemaless—other than the primary key, you do not need to define any extra attributes or data types when you create a table.
Here is the YAML syntax for DynamoDB table creation with partition and sort keys.
The syntax on OP is almost correct. I have just formatted with proper quotes and rearranged the order of the properties.
AWSTemplateFormatVersion: "2010-09-09"
Resources:
usersTable:
Type: "AWS::DynamoDB::Table"
Properties:
AttributeDefinitions:
-
AttributeName: "userId"
AttributeType: "S"
-
AttributeName: "noteId"
AttributeType: "S"
KeySchema:
-
AttributeName: "userId"
KeyType: "HASH"
-
AttributeName: "noteId"
KeyType: "RANGE"
ProvisionedThroughput:
ReadCapacityUnits: "5"
WriteCapacityUnits: "5"
TableName: "notes_serverless"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With