在 Node.js(AWS SDK v3)中查詢 DynamoDB GSI
查詢 global secondary index 就是一個平常的 Query 再加一個參數:IndexName。key condition 接著鎖定的是索引的 key,而非表格的 — 這裡 AlbumTitle-index 讓我們能依專輯抓取歌曲,這是 base table(Artist + SongTitle)不做 scan 就無法服務的存取模式。
Code
import {DynamoDBClient, QueryCommand} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
const items = [];
let lastEvaluatedKey;
do {
const response = await client.send(
new QueryCommand({
TableName: 'Music',
IndexName: 'AlbumTitle-index',
KeyConditionExpression: '#hashKey = :hashKeyValue',
ExpressionAttributeNames: {
'#hashKey': 'AlbumTitle'
},
ExpressionAttributeValues: {
':hashKeyValue': {S: 'Danzon'}
},
ExclusiveStartKey: lastEvaluatedKey
})
);
items.push(...(response.Items ?? []));
lastEvaluatedKey = response.LastEvaluatedKey;
} while (lastEvaluatedKey);
console.log(`Found ${items.length} 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 執行後續的GetItem,或加寬投影。 - GSI 中 key 並非唯一 — 許多項目可共用同一個索引 key,而缺少索引 key 屬性的項目就是不會出現(也就是 sparse-index 模式)。
- 分頁 — 與表格查詢相同:每頁最多 1 MB,把
LastEvaluatedKey→ExclusiveStartKey迴圈,直到它為undefined。
改用視覺化操作
DynamoDB Expression Builder 會為索引查詢建立 key condition 與 name/value map 並複製程式碼。
想在表單中瀏覽表格的索引並執行 GSI 查詢 — 分頁格線、複製產生的 SDK v3 程式碼 — 下載 DynoTable。
相關範例
- 在 Python 中查詢 DynamoDB GSI — 以 boto3 執行相同的索引查詢。
- 使用 AWS CLI 查詢 DynamoDB GSI — 從 shell 執行相同的索引查詢。
- 在 Node.js 中使用 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
- Using Global Secondary Indexes in DynamoDB — Amazon DynamoDB Developer Guide
- Paginating table query results — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。