You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环生成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 S for strings, N for numbers, and B for binary data in AttributeDefinitions.
  • Billing Modes: Choose between PAY_PER_REQUEST (on-demand) or ProvisionedThroughput (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_configs from an external file (like JSON or CSV) using json.load() or a CSV parser, instead of hardcoding them.

内容的提问来源于stack exchange,提问作者j panton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:27:53