要解决"AWS DynamoDB:按需索引的定价"问题并包含代码示例,您可以按照以下步骤进行:
步骤 1:了解 DynamoDB 索引的定价
步骤 2:创建一个 DynamoDB 表和索引
步骤 3:根据查询需求添加索引
步骤 4:编写代码示例
以下是一个使用 Python 和 Boto3(AWS SDK for Python)的示例代码,用于创建 DynamoDB 表格和索引,并执行查询操作:
import boto3
# 创建 DynamoDB 客户端
dynamodb = boto3.client('dynamodb')
# 创建表格
response = dynamodb.create_table(
TableName='my_table',
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'N'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# 创建索引
response = dynamodb.update_table(
TableName='my_table',
AttributeDefinitions=[
{
'AttributeName': 'name',
'AttributeType': 'S'
}
],
GlobalSecondaryIndexUpdates=[
{
'Create': {
'IndexName': 'name-index',
'KeySchema': [
{
'AttributeName': 'name',
'KeyType': 'HASH'
}
],
'Projection': {
'ProjectionType': 'ALL'
},
'ProvisionedThroughput': {
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
}
}
]
)
# 查询操作
response = dynamodb.query(
TableName='my_table',
IndexName='name-index',
KeyConditionExpression='name = :name',
ExpressionAttributeValues={
':name': {'S': 'John'}
}
)
# 处理查询结果
for item in response['Items']:
print(item)
请注意,这只是一个简单的示例,您可以根据您的实际需求进行修改和扩展。
希望这个解决方案能够帮助到您!