Python操作Dynamo

创建Dynamo表

import boto3
dynamodb = boto3.resource('dynamodb')

# Create the DynamoDB table.
table = dynamodb.create_table(
    TableName='waihui',
    
    AttributeDefinitions=[        
        {
            'AttributeName': 'code',
            'AttributeType': 'S'
        }
        
        
    ],
    KeySchema=[
        {
            'AttributeName': 'code',
            'KeyType': 'HASH'
        }
        
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    }
    
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='waihui')
# Print out some data about the table.
print(table.item_count)

注意事项:1.AttributeDefinitions与KeySchema项目保持一致。

2.ProvisionedThroughput为系统默认,必须设置

Dynamo表中插入项目

import boto3
import decimal
# Get the service resource.
dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('waihui')

table.put_item(
   Item={
        'code': 'USDCAD',
        'high': Decimal('1.3200'),
        'low': Decimal('1.3000'),
    }
)

如果插入项目中数值为小数,需要使用Decimal转换为Dynamo数据类型N。

获取单一项目

import boto3    
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('waihui')
response = table.get_item(
   Key={
        'code': 'USDCAD'        
    }
)
item = response['Item']
print(item)

更新项目

import boto3
import decimal
# Get the service resource.
dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('waihui')
table.update_item(
    Key={
        'code': 'USDCAD'
    },
    UpdateExpression='SET low = :val1',
    ExpressionAttributeValues={
        ':val1': Decimal('1.2980')
    }
)

批量更新项目

with table.batch_writer() as batch:
    for i in range(50):
        batch.put_item(
            Item={
                'account_type': 'anonymous',
                'username': 'user' + str(i),
                'first_name': 'unknown',
                'last_name': 'unknown'
            }
        )

删除项目

import boto3
# Get the service resource.
dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('waihui')

table.delete_item(
   Key={
        'code': 'USDCAD'        
    }
)

删除表

import boto3
# Get the service resource.
dynamodb = boto3.resource('dynamodb')    
table = dynamodb.Table('waihui')
table.delete()

扫描查询

response = table.scan(
    FilterExpression=Attr('first_name').begins_with('J') & Attr('account_type').eq('super_user')
)
items = response['Items']
print(items)

可以设定记录中的key值为查询扫描条件

response = table.scan(
    FilterExpression=Attr('address.state').eq('CA')
)
items = response['Items']
print(items)
添加新评论