Add new Global Secondary Index (GSI) to an existing DynamoDB table

Many times we feel the need to have another GSI to an exiting table like we need to order the query result by updatedAt column.

In DynamoDB that is possible without destroying the existing table. This is how to do it. Make sure you have aws-cli installed on your system and credentials configured.

  1. Create a new json file named gsi.json with the definition of the GSI like the one shown below
{
  "AttributeDefinitions": [
    {
      "AttributeName": "someId",
      "AttributeType": "S"
    },
    {
      "AttributeName": "updatedAt",
      "AttributeType": "S"
    }
  ],
  "GlobalSecondaryIndexUpdates": [
    {
      "Create": {
        "IndexName": "someIdupdatedAtIndex",
        "KeySchema": [
          {
            "AttributeName": "someId",
            "KeyType": "HASH"
          },
          {
            "AttributeName": "updatedAt",
            "KeyType": "RANGE"
          }
        ],
        "Projection": {
          "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
          "ReadCapacityUnits": 5,
          "WriteCapacityUnits": 5
        }
      }
    }
  ]
}

2. Run this command from the CLI:

aws dynamodb update-table --table-name my-table --cli-input-json file://gsi.json

If you want to update the local dynamodb table the run

aws dynamodb update-table --table-name my-table --cli-input-json file://gsi.json --endpoint-url http://localhost:8000

This will create a new index but you have to wait till the index is created to use it. The time will depend on the rows in table.

Leave a Reply

Your email address will not be published. Required fields are marked *