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


Borislav Hadzhiev

Fri Apr 15 20222 min read

Updated - Fri Apr 15 2022

Adding a Dynamodb GSI in AWS CDK #

In order 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

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.