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

avatar

Borislav Hadzhiev

Sun May 02 20212 min read

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:

lib/cdk-starter-stack.ts
import * as dynamodb from '@aws-cdk/aws-dynamodb'; import * as cdk from '@aws-cdk/core'; 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:

shell
npx 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 #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee