0
votes

I am trying to create a dynamodb table using boto3. But I am getting the following error:

"botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the CreateTable operation: Invalid KeySchema: The first KeySchemaElement is not a HASH key type"

More info: I don't have any global table existing in my account.

Code I tried with:

import boto3

client = boto3.client('dynamodb')

response = client.create_table(
    AttributeDefinitions=[
        {
            'AttributeName': 'student_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'student_name',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'course_id',
            'AttributeType': 'S'
        }
    ],
    TableName='students',
    KeySchema=[
        {
            'AttributeName': 'student_name',
            'KeyType': 'HASH'
        },
{
            'AttributeName': 'student_id',
            'KeyType': 'RANGE'
        },
    ],
    LocalSecondaryIndexes=[
        {
            'IndexName': 'course_id',
            'KeySchema': [
                {
                    'AttributeName': 'course_id',
                    'KeyType': 'RANGE'
                }
            ],
            'Projection': {
                'ProjectionType': 'ALL'
            }
        },
    ],
    BillingMode='PAY_PER_REQUEST',

)
1

1 Answers

1
votes

You should explicitly specify the HASH key for the LSI too.

import boto3

client = boto3.client('dynamodb')

response = client.create_table(
    AttributeDefinitions=[
        {
            'AttributeName': 'student_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'student_name',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'course_id',
            'AttributeType': 'S'
        }
    ],
    TableName='students',
    KeySchema=[
        {
            'AttributeName': 'student_name',
            'KeyType': 'HASH'
        },
        {
            'AttributeName': 'student_id',
            'KeyType': 'RANGE'
        },
    ],
    LocalSecondaryIndexes=[
        {
            'IndexName': 'course_id',
            'KeySchema': [
                {
                    'AttributeName': 'student_name',
                    'KeyType': 'HASH'
                },
                {
                    'AttributeName': 'course_id',
                    'KeyType': 'RANGE'
                }
            ],
            'Projection': {
                'ProjectionType': 'ALL'
            }
        },
    ],
    BillingMode='PAY_PER_REQUEST',

)