Reading timeยท2 min
To add a Global Secondary Index to a Dynamodb Table in AWS CDK, we have to use the addGlobalSecondaryIndex method on an instance of the Table class.
Let's look at a simple example where we create a dynamodb table and add a global secondary index to it:
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as cdk from 'aws-cdk-lib'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐ create Dynamodb table const table = new dynamodb.Table(this, id, { partitionKey: {name: 'todoId', type: dynamodb.AttributeType.STRING}, sortKey: {name: 'createdAt', type: dynamodb.AttributeType.NUMBER}, billingMode: dynamodb.BillingMode.PROVISIONED, readCapacity: 1, writeCapacity: 1, removalPolicy: cdk.RemovalPolicy.DESTROY, }); // ๐ add global secondary index table.addGlobalSecondaryIndex({ indexName: 'userIdIndex', partitionKey: {name: 'userId', type: dynamodb.AttributeType.STRING}, sortKey: {name: 'status', type: dynamodb.AttributeType.STRING}, readCapacity: 1, writeCapacity: 1, projectionType: dynamodb.ProjectionType.ALL, }); } }
Let's go over the code snippet.
addGlobalSecondaryIndex
method. The props we have passed to the method are:indexName
- the name of the global secondary indexpartitionKey
- the partition key attribute for the global secondary indexsortKey
- the sort key attribute for the global secondary indexreadCapacity
and writeCapacity
- the capacity for the global secondary
index. These properties can only be provided if the table is configured with
PROVISIONED
capacity. By default readCapacity
and writeCapacity
are set
to 5
.projectionType
- which attributes should be projected into the global
secondary index. By default all attributes are projected into the GSI, so we
could have omitted this property.I'll deploy the stack:
npx aws-cdk deploy
After a deployment, the dynamodb table has been provisioned and the global secondary index has been added to the table:
I've also written a guide on how to provision and configure a Dynamodb table using AWS CDK.
You can learn more about the related topics by checking out the following tutorials: