'Create Global Secondary Index (GSI) for DynamoDB using Boto3 in Python

I'm creating a DynamoDB table using the Python boto3 package:

import boto3
ddb = boto3.resource('dynamodb')
table = ddb.create_table(
    TableName = "MyTable",
    KeySchema = [
        {
            'AttributeName': 'key1',
            'KeyType': 'HASH'
        },
        {
            'AttributeName': 'key2',
            'KeyType': 'RANGE'
        }
    ],
    AttributeDefinitions = [
        {
            'AttributeName': 'key1',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'key2',
            'AttributeType': 'S'
        }
    ],
    ProvisionedThroughput = {
        'ReadCapacityUnits': 1,
        'WriteCapacityUnits': 1
    }
)

I want to know if it is possible to create a global secondary key (GSI) when creating the table using this package, and how to do it. I see that it is possible to update a table to contain a GSI, though (see here).



Solution 1:[1]

Taking your example, just add the GlobalSecondaryIndexes attribute to create_table:

import boto3
ddb = boto3.resource('dynamodb')
table = ddb.create_table(
    TableName = "MyTable",
    KeySchema = [
        {
            'AttributeName': 'key1',
            'KeyType': 'HASH'
        },
        {
            'AttributeName': 'key2',
            'KeyType': 'RANGE'
        }
    ],
    GlobalSecondaryIndexes=[
        {
            'IndexName': 'idx1',
            'KeySchema': [
               {
                  'AttributeName': 'key2',
                  'KeyType': 'HASH'
               }
             ],
             'Projection': {
               'ProjectionType': 'ALL'
             },
             'ProvisionedThroughput': {
                  'ReadCapacityUnits': 1,
                  'WriteCapacityUnits': 1
             }
        }
    ],
    AttributeDefinitions = [
        {
            'AttributeName': 'key1',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'key2',
            'AttributeType': 'S'
        }
    ],
    ProvisionedThroughput = {
        'ReadCapacityUnits': 1,
        'WriteCapacityUnits': 1
    }
)

GSI on MyTable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pankaj Saini