AWS DynamoDB snippets
How to create a table for DynamoDB 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 table named simpsonsEpisodes
, with two Primary Key:
- No_Season as HASH key, numeric data type;
- No_Inseason as SORT key, numeric 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:
response = dynamodbClient.create_table(
TableName=TABLENAME,
AttributeDefinitions=[
{
"AttributeName": "No_Season",
"AttributeType": "N"
},
{
"AttributeName": "No_Inseason",
"AttributeType": "N"
}
],
KeySchema=[
{
"AttributeName": "No_Season",
"KeyType": "HASH"
},
{
"AttributeName": "No_Inseason",
"KeyType": "RANGE"
}
],
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
}
)
print(response)
except Exception as e:
print("Error creating table %s:" % (TABLENAME))
print(e)
'TableDescription': {'AttributeDefinitions': [{'AttributeName': 'No_Inseason', 'AttributeType': 'N'}, {'AttributeName': 'No_Season', 'AttributeType': 'N'}], 'TableName': 'simpsonsEpisodes', 'KeySchema': [{'AttributeName': 'No_Season', 'KeyType': 'HASH'}, {'AttributeName': 'No_Inseason', 'KeyType': 'RANGE'}], 'TableStatus': 'CREATING', 'CreationDateTime': datetime.datetime(2022, 12, 7, 17, 16, 43, 861000, tzinfo=tzlocal()), 'ProvisionedThroughput': {'NumberOfDecreasesToday': 0, 'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}, 'TableSizeBytes': 0, 'ItemCount': 0, 'TableArn': 'arn:aws:dynamodb:us-east-1:526274010548:table/simpsonsEpisodes', 'TableId': '68a43e23-8341-4de6-ba2c-d89e650166b8'}, 'ResponseMetadata': {'RequestId': '4SRRKHU0ELP75D8N4MQ05S79GBVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Wed, 07 Dec 2022 16:16:43 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '608', 'connection': 'keep-alive', 'x-amzn-requestid': '4SRRKHU0ELP75D8N4MQ05S79GBVV4KQNSO5AEMVJF66Q9ASUAAJG', 'x-amz-crc32': '1365729830'}, 'RetryAttempts': 0}}