AWS DynamoDB snippets

How to add a GSI on a DynamoDB table in Python boto3

Please note that this snippet is part of the DynamoDB-Simpsons-episodes-full-example repository on GitHub.

Let's say you want to create a Global Secondary Index to an existent table named simpsonsEpisodes, with the following HASH key:

  • OriginalAirDate as HASH key, string data type;

First of all, you have to create a Client (follow these steps) and then you can use the following code:

TABLENAME='simpsonsEpisodes'
try:
    resp = dynamodbClient.update_table(
        TableName=TABLENAME,
        AttributeDefinitions=[
            {
                "AttributeName": "OriginalAirDate",
                "AttributeType": "S"
            },
        ],
        GlobalSecondaryIndexUpdates=[
            {
                "Create": {
                    "IndexName": "AirDateIndex",
                    "KeySchema": [
                        {
                            "AttributeName": "OriginalAirDate",
                            "KeyType": "HASH"
                        }
                    ],
                    "Projection": {
                        "ProjectionType": "ALL"
                    },
                    "ProvisionedThroughput": {
                        "ReadCapacityUnits": 1,
                        "WriteCapacityUnits": 1,
                    }
                }
            }
        ],
    )
    print("AirDateIndex added!")
except Exception as e:
    print("Error adding AirDateIndex:")
    print(e)
AirDateIndex added!

Back to AWS DynamoDB cookbook page