logo
post image

Create DynamoDB Tables (with Index) using Node.js

Tables can be created in DynamoDB using the CreateTableCommand method of the AWS DynamoDB Javascript SDK.

Install the module through the command :

npm install @aws-sdk/client-dynamodb

Our Sample Table

We are going to create a table named Posts. This table has a simple primary key (partition key) named PostID, whose data type is Number (N).

This table also has a Global Secondary Index named PostsVisibleIndex. The index has a composite primary key — PostVisible (partition key) and PostID (sort key). The data type of PostVisible is String (S).

The table Posts is basically going to hold all posts, while the index PostsVisibleIndex is going to hold all visible posts.

Now that we have planned the table details, we can use CreateTableCommand method to create the table, along with the index.

The below code examples assumes 3 environment variables have been set — AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY & AWS_REGION.

const { DynamoDBClient, CreateTableCommand } = require("@aws-sdk/client-dynamodb")

// init dynamodb client
const dbclient = new DynamoDBClient({ region: process.env.AWS_REGION })

// create table and index
await dbclient.send(new CreateTableCommand({
	AttributeDefinitions: [
    { AttributeName: 'PostID', AttributeType: 'N' },
    { AttributeName: 'PostVisible', AttributeType: 'S' }
  ],
  TableName: 'Posts',
	KeySchema: [
    { AttributeName: 'PostID', KeyType: 'HASH' }
  ],
  BillingMode: 'PAY_PER_REQUEST',
  GlobalSecondaryIndexes: [
    {
      IndexName: 'PostsVisibleIndex',
      KeySchema: [
        { AttributeName: 'PostVisible', KeyType: 'HASH' },
        { AttributeName: 'PostID', KeyType: 'RANGE' }
      ],
      Projection: {
        ProjectionType: 'ALL'
      }
    }
  ]
}))
  • KeySchema will hold the primary key details of the table
  • GlobalSecondaryIndexes.KeySchema will hold the primary key details of the index
  • AttributeDefinitions will hold the attribute definitions of primary keys of both the table and index
  • The default value for BillingMode is PAY_PER_REQUEST
  • Setting ProjectionType to ALL will include all other attributes of the table in the index also
  • If there is no need to create the index, we can remove all properties related to the index from the request data
  • For full information about CreateTableCommand, check the AWS documentation