Add a Dynamodb Global Secondary Index in AWS CDK [GSI]

Borislav Hadzhiev

2 min


# Adding a Dynamodb GSI in AWS CDK

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.

The code for this article is available on GitHub

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.

  1. We created a dynamodb table with provisioned capacity
  2. We created a Global secondary index on the table using the addGlobalSecondaryIndex method. The props we have passed to the method are:
  • indexName - the name of the global secondary index
  • partitionKey - the partition key attribute for the global secondary index
  • sortKey - the sort key attribute for the global secondary index
  • readCapacity 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:

table with gsi

I've also written a guide on how to provision and configure a Dynamodb table using AWS CDK.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev