AWS DynamoDB是一种无服务器的NoSQL数据库服务,可用于数据收集和分析应用程序。下面是一个使用AWS SDK for Python(Boto3)的示例代码,演示如何在DynamoDB中创建表、插入数据和查询数据。
首先,确保已安装boto3库。您可以使用以下命令进行安装:
pip install boto3
接下来,使用以下代码示例创建DynamoDB表:
import boto3
# 创建DynamoDB客户端
dynamodb = boto3.client('dynamodb')
# 定义表的属性
table_name = 'my-data-table'
attribute_definitions = [
{
'AttributeName': 'id',
'AttributeType': 'N'
},
{
'AttributeName': 'timestamp',
'AttributeType': 'N'
}
]
key_schema = [
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
{
'AttributeName': 'timestamp',
'KeyType': 'RANGE'
}
]
provisioned_throughput = {
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
# 创建表
response = dynamodb.create_table(
TableName=table_name,
AttributeDefinitions=attribute_definitions,
KeySchema=key_schema,
ProvisionedThroughput=provisioned_throughput
)
print('Table created:', response)
接下来,使用以下代码示例向DynamoDB表中插入数据:
import boto3
# 创建DynamoDB客户端
dynamodb = boto3.client('dynamodb')
# 定义要插入的数据
table_name = 'my-data-table'
item = {
'id': {'N': '1'},
'timestamp': {'N': '1633123200'},
'data': {'S': 'example data'}
}
# 插入数据
response = dynamodb.put_item(
TableName=table_name,
Item=item
)
print('Data inserted:', response)
最后,使用以下代码示例从DynamoDB表中查询数据:
import boto3
# 创建DynamoDB客户端
dynamodb = boto3.client('dynamodb')
# 定义查询条件
table_name = 'my-data-table'
query_key = {'id': {'N': '1'}}
projection_expression = 'data'
# 查询数据
response = dynamodb.get_item(
TableName=table_name,
Key=query_key,
ProjectionExpression=projection_expression
)
data = response['Item']['data']['S']
print('Data retrieved:', data)
以上代码示例演示了如何使用AWS DynamoDB来创建表、插入数据和查询数据。您可以根据自己的需求进行修改和扩展。