如何用循环生成JSON格式批量创建AWS DynamoDB表?
Got it, let's tackle this problem—batch-creating DynamoDB tables with boto3 without manually writing JSON for each one is totally doable. Here's a practical, scalable approach tailored to your needs:
Batch Create DynamoDB Tables with Boto3
Instead of writing repetitive JSON for each table, we'll define all your table metadata in a structured Python list, then loop through it to create tables automatically. This keeps your code clean and makes adding/editing tables a breeze.
Step 1: Define Your Table Configurations
First, organize all your table details (names, keys, attributes, and settings) into a list of dictionaries. Each dictionary represents one table's creation parameters.
Step 2: Full Code Example
import boto3 # Initialize the DynamoDB resource dynamodb = boto3.resource('dynamodb') # Define your table configurations here # Extend this list with all your tables and their properties table_configs = [ { 'TableName': 'Users', 'KeySchema': [ {'AttributeName': 'user_id', 'KeyType': 'HASH'} # Partition key ], 'AttributeDefinitions': [ {'AttributeName': 'user_id', 'AttributeType': 'S'}, {'AttributeName': 'email', 'AttributeType': 'S'}, {'AttributeName': 'age', 'AttributeType': 'N'} ], # Use PAY_PER_REQUEST for on-demand billing instead of provisioned capacity 'BillingMode': 'PAY_PER_REQUEST' }, { 'TableName': 'Orders', 'KeySchema': [ {'AttributeName': 'order_id', 'KeyType': 'HASH'}, # Partition key {'AttributeName': 'user_id', 'KeyType': 'RANGE'} # Sort key ], 'AttributeDefinitions': [ {'AttributeName': 'order_id', 'AttributeType': 'S'}, {'AttributeName': 'user_id', 'AttributeType': 'S'}, {'AttributeName': 'order_total', 'AttributeType': 'N'}, {'AttributeName': 'order_date', 'AttributeType': 'S'} ], 'ProvisionedThroughput': { 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } } ] # Loop through configurations to create tables for config in table_configs: try: # Unpack the config dictionary to pass parameters to create_table table = dynamodb.create_table(**config) # Wait for the table to be fully active (critical for subsequent operations) table.wait_until_exists() print(f"✅ Successfully created table: {config['TableName']}") except Exception as e: print(f"❌ Error creating table {config['TableName']}: {str(e)}")
Key Details to Note
- Attribute Types: Use
Sfor strings,Nfor numbers, andBfor binary data inAttributeDefinitions. - Billing Modes: Choose between
PAY_PER_REQUEST(on-demand) orProvisionedThroughput(fixed capacity) based on your usage needs. - Async Creation: The
wait_until_exists()method ensures we don't proceed until the table is ready—DynamoDB creates tables asynchronously, so this prevents race conditions. - Scalability: For larger sets of tables, you can load
table_configsfrom an external file (like JSON or CSV) usingjson.load()or a CSV parser, instead of hardcoding them.
内容的提问来源于stack exchange,提问作者j panton
相关产品推荐
相关产品推荐

