dynamodb boto3

b为二进制  N为数字  S为字符串

2. Python (Boto3) 操作示例
初始化客户端
python
import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
client = boto3.client('dynamodb')
创建表
python

table = dynamodb.create_table(
    TableName='Users',
    KeySchema=[
        {'AttributeName': 'user_id', 'KeyType': 'HASH'},  # 分区键
        {'AttributeName': 'email', 'KeyType': 'RANGE'}    # 排序键(可选)
    ],
    AttributeDefinitions=[
        {'AttributeName': 'user_id', 'AttributeType': 'S'},  # S=String
        {'AttributeName': 'email', 'AttributeType': 'S'}
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    },
    # 按需模式(无预置容量)
    # BillingMode='PAY_PER_REQUEST'  
)

table.wait_until_exists()  # 等待表创建完成
CRUD 操作
python

table = dynamodb.Table('Users')

# 插入数据
table.put_item(
    Item={
        'user_id': '123',
        'email': 'user@example.com',
        'name': 'John Doe',
        'age': 30,
        'address': {
            'city': 'New York',
            'zip': '10001'
        }
    }
)

# 获取数据
response = table.get_item(
    Key={'user_id': '123', 'email': 'user@example.com'}
)
item = response.get('Item')

# 更新数据
table.update_item(
    Key={'user_id': '123', 'email': 'user@example.com'},
    UpdateExpression='SET age = :val1, address.city = :val2',
    ExpressionAttributeValues={
        ':val1': 31,
        ':val2': 'Brooklyn'
    }
)

# 删除数据
table.delete_item(
    Key={'user_id': '123', 'email': 'user@example.com'}
)
查询与扫描
python

# 查询(高效,使用主键)
response = table.query(
    KeyConditionExpression=Key('user_id').eq('123')
)

# 扫描(全表扫描,谨慎使用)
response = table.scan(
    FilterExpression=Attr('age').gt(25)
)
批量操作
python

with table.batch_writer() as batch:
    batch.put_item(Item={'user_id': '124', 'email': 'user2@example.com'})
    batch.delete_item(Key={'user_id': '123', 'email': 'user@example.com'})
3. 高级功能
全局二级索引 (GSI)
python

table = dynamodb.create_table(
    # ...其他参数...
    GlobalSecondaryIndexes=[
        {
            'IndexName': 'EmailIndex',
            'KeySchema': [
                {'AttributeName': 'email', 'KeyType': 'HASH'}
            ],
            'Projection': {'ProjectionType': 'ALL'},
            'ProvisionedThroughput': {
                'ReadCapacityUnits': 5,
                'WriteCapacityUnits': 5
            }
        }
    ]
)
条件写入
python

table.put_item(
    Item={'user_id': '125', 'email': 'new@example.com'},
    ConditionExpression='attribute_not_exists(user_id)'
)
事务操作
python

client.transact_write_items(
    TransactItems=[
        {
            'Put': {
                'TableName': 'Users',
                'Item': {'user_id': '126', 'email': 'tx@example.com'}
            }
        },
        {
            'Update': {
                'TableName': 'Orders',
                'Key': {'order_id': '1001'},
                'UpdateExpression': 'SET user_id = :uid',
                'ExpressionAttributeValues': {':uid': '126'}
            }
        }
    ]
)


# 使用ProjectionExpression减少返回数据
table.scan(
    ProjectionExpression='user_id, email'
)

# 分页处理大数据集
paginator = client.get_paginator('scan')
for page in paginator.paginate(TableName='Users'):
    process_page(page['Items'])
成本控制
使用 按需容量模式(BillingMode='PAY_PER_REQUEST')

为不常访问的数据设置 TTL 自动过期

启用 Auto Scaling 自动调整容量

5. 与其他服务集成
Lambda触发器
python

# 示例:当DynamoDB有变更时触发Lambda
import json

def lambda_handler(event, context):
    for record in event['Records']:
        if record['eventName'] == 'INSERT':
            new_item = record['dynamodb']['NewImage']
            print("New item:", json.dumps(new_item))
API Gateway直接集成
yaml

# SAM模板示例
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      DefinitionUri: swagger.yaml
6. 监控与维护
python

# 获取表指标
cloudwatch = boto3.client('cloudwatch')
response = cloudwatch.get_metric_statistics(
    Namespace='AWS/DynamoDB',
    MetricName='ConsumedReadCapacityUnits',
    Dimensions=[{'Name': 'TableName', 'Value': 'Users'}],
    StartTime=datetime.utcnow() - timedelta(hours=1),
    EndTime=datetime.utcnow(),
    Period=300,
    Statistics=['Sum']
)
故障排查
ProvisionedThroughputExceededException:增加容量或优化查询

ConditionalCheckFailedException:条件写入失败

使用DynamoDB Local:本地开发测试

bash

docker run -p 8000:8000 amazon/dynamodb-local
通过以上代码和策略,您可以高效地使用 DynamoDB 构建可扩展的应用程序。根据具体场景调整表设计和访问模式是关键。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值