Node.js(AWS SDK v3)中查询 DynamoDB GSI
查询一个全局二级索引就是一次普通的 Query 加上一个参数:IndexName。键条件随即针对索引的键,而非表的键——这里 AlbumTitle-index 让我们能按专辑获取歌曲,而基表(Artist + SongTitle)不做扫描就无法服务这种访问模式。
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使用索引的分区键(以及可选的排序键)——这里是AlbumTitle——运算符与表查询相同。- 仅最终一致性 — GSI 从基表异步复制。在 GSI 查询上传入
ConsistentRead: true并不会将其升级;它会以ValidationException失败。(本地二级索引确实支持强一致性。) - 你只得到被投影的属性 — 一次 GSI 查询返回索引所投影的内容(
ALL、KEYS_ONLY或INCLUDE列出的属性),且不能从基表获取其余部分。需要一个未被投影的属性?请对表键后续做一次GetItem,或加宽投影。 - GSI 中的键不唯一 — 许多项目可以共享同一个索引键,而缺少该索引键属性的项目根本不会出现(这就是稀疏索引模式)。
- 分页 — 与表查询相同:每页最多 1 MB,循环
LastEvaluatedKey→ExclusiveStartKey直到它为undefined。
可视化操作
DynamoDB Expression Builder 会为索引查询构建键条件 + 名称/值映射并复制代码。
想浏览一张表的索引并用表单运行 GSI 查询——分页网格、复制生成的 SDK v3 代码——请下载 DynoTable。
相关示例
- Python 中查询 DynamoDB GSI — 用 boto3 完成同样的索引查询。
- 使用 AWS CLI 查询 DynamoDB GSI — 在 shell 中完成同样的索引查询。
- Node.js 中的 DynamoDB Query — 查询基表。
- GSI vs. LSI — 哪种索引类型契合该访问模式。
- 为什么 GSI 是最终一致性的 — 复制延迟的解释。
- "The table does not have the specified index" — 索引名不匹配(GSI 名称区分大小写)。
- "Consistent reads are not supported on global secondary indexes" — 为什么一致性读取标志在 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
Last verified 2026-07-13 against the official AWS documentation linked above.