模块 3:查询和二级索引
了解如何使用二级索引实现对 DynamoDB 表的更多查询模式
简介
在本模块中,我们将介绍如何使用二级索引。在上一个模块中,我们探讨了在给定复合主键元素 Author 和 Title 的情况下,如何检索书籍的更多信息。但是,实际应用中,您可能希望检索某特定类别的所有图书,例如技术或传记类。遗憾的是在上一模块创建的表中,Category 并不是表的主键字段。不过,您可以创建二级索引来实现此访问模式。下面的操作步骤展示如何在应用程序中实现此访问模式。
时长
15 分钟
前提条件
- 已有一个 AWS 账户。如果您还没有 AWS 账户,请先创建和配置账户。更多信息,请参阅设置环境。
运行 pip install boto3 命令安装的 AWS SDK
操作步骤
步骤 1:创建二级索引
您可以在创建表时创建全局二级索引,也可以在创建表之后指定全局二级索引。以下代码将为 Books 表创建全局二级索引。二级索引相关的属性的定义方式与创建表和定义主键的方式类似。
import boto3
# Boto3 is the AWS SDK library for Python.
# You can use the low-level client to make API calls to DynamoDB.
client = boto3.client('dynamodb', region_name='us-east-1')
try:
resp = client.update_table(
TableName=\"Books\",
# Any attributes used in your new global secondary index must be declared in AttributeDefinitions.
AttributeDefinitions=[
{
"AttributeName": "Category",
"AttributeType": "S"
},
],
# This is where you add, update, or delete any global secondary indexes on your table.
GlobalSecondaryIndexUpdates=[
{
"Create": {
# You need to name your index and specifically refer to it when using it for queries.
"IndexName": "CategoryIndex",
# Like the table itself, you need to specify the key schema for an index.
# For a global secondary index, you can use a simple or composite key schema.
"KeySchema": [
{
"AttributeName": "Category",
"KeyType": "HASH"
}
],
# You can choose to copy only specific attributes from the original item into the index.
# You might want to copy only a few attributes to save space.
"Projection": {
"ProjectionType": "ALL"
},
# Global secondary indexes have read and write capacity separate from the underlying table.
"ProvisionedThroughput": {
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
}
}
}
],
)
print("Secondary index added!")
except Exception as e:
print("Error updating table:")
print(e)
步骤 2:使用二级索引查询
现在,您已创建了 CategoryIndex 索引,可以使用它来检索特定类别的所有图书。
import boto3
dynamodb = boto3.client('dynamodb', region_name='us-east-1')
resp = dynamodb.execute_statement(Statement='SELECT * FROM Books.CategoryIndex WHERE Category = \'Technology\'')
print(resp['Items'])