2

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).

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.