在 Python(boto3)中查詢 DynamoDB GSI
查詢 global secondary index 就是一個平常的 query 再加一個參數:IndexName。key condition 接著鎖定的是索引的 key,而非表格的 — 這裡 AlbumTitle-index 讓我們能依專輯抓取歌曲,這是 base table(Artist + SongTitle)不做 scan 就無法服務的存取模式。
Code
import boto3
client = boto3.client("dynamodb")
paginator = client.get_paginator("query")
items = []
for page in paginator.paginate(
TableName="Music",
IndexName="AlbumTitle-index",
KeyConditionExpression="#hashKey = :hashKeyValue",
ExpressionAttributeNames={"#hashKey": "AlbumTitle"},
ExpressionAttributeValues={":hashKeyValue": {"S": "Danzon"}},
):
items.extend(page["Items"])
print(f"Found {len(items)} songs on the album")說明
IndexName— 指名要查詢的 GSI(TableName仍為必需)。KeyConditionExpression使用索引的 partition(與選用的 sort)key — 這裡是AlbumTitle— 運算子與表格查詢相同。- 僅最終一致 — GSI 從 base table 非同步複製。對 GSI 查詢傳入
ConsistentRead=True並不會升級它;它會引發ValidationException。(local secondary index 確實支援強一致。) - 你只會拿到已投影的屬性 — GSI 查詢回傳索引所投影的內容(
ALL、KEYS_ONLY,或INCLUDE列出的屬性),且無法從 base table 取回其餘部分。需要未投影的屬性?以 table key 執行後續的get_item,或加寬投影。 - GSI 中 key 並非唯一 — 許多項目可共用同一個索引 key,而缺少索引 key 屬性的項目就是不會出現(也就是 sparse-index 模式)。
- 分頁 —
client.get_paginator("query")會像表格查詢一樣跨各頁追蹤LastEvaluatedKey;每個page都帶有一個Itemslist。 - 在 resource API 上,相同的查詢是
table.query(IndexName="AlbumTitle-index", KeyConditionExpression=Key("AlbumTitle").eq("Danzon")),使用原生的 Python 值。
改用視覺化操作
DynamoDB Expression Builder 會為索引查詢建立 key condition 與 name/value map 並複製可執行的 boto3 程式碼。
想在表單中瀏覽表格的索引並執行 GSI 查詢 — 分頁格線、複製為程式碼 — 下載 DynoTable。
相關範例
- 在 Node.js 中查詢 DynamoDB GSI — 以 AWS SDK v3 執行相同的索引查詢。
- 使用 AWS CLI 查詢 DynamoDB GSI — 從 shell 執行相同的索引查詢。
- 在 Python 中使用 DynamoDB Query — 查詢 base table。
- GSI vs. LSI — 哪種索引型別適合該存取模式。
- 為什麼 GSI 是最終一致 — 複製延遲的說明。
- "The table does not have the specified index" — 索引名稱不符(GSI 名稱區分大小寫)。
- "Consistent reads are not supported on global secondary indexes" — 為什麼 consistent-read 旗標在 GSI 上會失敗。
References
- Query — Amazon DynamoDB API Reference
- DynamoDB.Paginator.Query — Boto3 documentation
- Using Global Secondary Indexes in DynamoDB — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。