DynamoDB 可讓您建立次要索引,以說明資料表中的其他資料存取模式。次要索引是一種為 DynamoDB 資料表增加查詢靈活性的強大方式。
DynamoDB 有兩類次要索引:全域次要索引和本機次要索引。在本部分,我們新增全域次要索引至您的 Category 屬性,這將讓您擷取特殊類別中的所有書。
以下範例指令碼將全域次要索引新增至現有資料表。
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)
建立全域次要索引與建立資料表有許多相同之處。您為索引指定名稱、索引中的屬性、索引的索引鍵結構描述和佈建輸送量 (應用程式可從資料表或索引中取用的最大容量)。每個索引的佈建輸送量與資料表中的佈建輸送量是分開的。這可讓您定義輸送量粒度以滿足您的應用程式需要。
在終端機中執行以下命令,以新增全域次要索引。
$ python add_secondary_index.py
此指令碼新增稱為 CategoryIndex 的全域次要索引至您的 Books 資料表。