我正在开发 DynamoDB 数据模型,其中有一个名为“RequestGroup”的表,具有特定的主键 (PK) 和排序键 (SK) 属性。我还创建了一个名为“ReversedRGIndex”的全局二级索引 (GSI),以支持特定的查询模式。它基本上是一个倒排索引,这应该允许我像查询 PK 一样查询 SK。
Table Structure:
Table Name: RequestGroup
Primary Key (PK):
Attribute Name: PK
Attribute Type: String (S)
Sort Key (SK):
Attribute Name: SK
Attribute Type: String (S)
Secondary Index:
Index Name: ReversedRGIndex
Index Key Schema:
Partition Key (PK): SK
Sort Key (SK): PK
问题陈述: 我想使用 ReversedRGIndex 查询此 DynamoDB 表,以检索 SK 属性以“PR#”开头的所有项目。每条记录都有一个 PK,如下所示:“RequestGroup#123456”。此表中的常见 SK 记录可能有两个不同的 SK:PR# 或元数据。我只想过滤第一个(类似于..begins_with“PR#”)。因此,我无法指定我想要哪个 PK,因为我想要所有带有 PR# 的 SK,无论它们的 PK 如何。
当前的方法: 我对代码进行了简化,如下所示。
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
const client = new DynamoDBClient({});
exports.GetAllRules = async () => {
const params = {
TableName: "RequestGroup",
IndexName: 'ReversedRGIndex',
KeyConditionExpression: "BEGINS_WITH(PK, :pk_begins_with_pr)",
ExpressionAttributeValues: {
":pk_begins_with_pr": {"S": "PR#"},
},
};
const command = new QueryCommand(params);
const result = await client.send(command);
};
我之前尝试过的替代方案: 我尝试调整参数。就像仅使用“#PR”传递 ExpressionAttributeValues、使用 SK 而不是 PK 等。但是,到目前为止我无法找到解决方案。
在 DynamoDB 中,无论您是从基表还是索引进行查询,您都必须始终提供分区键的完整值。
在您的情况下,您在分区键上使用begins_with,这是行不通的。另一种方法是这样的:
GSIPK | PK |
---|---|
1 | PR#123 |
1 | PR#236 |
1 | 元数据#001 |
通过这种方式,您可以定义一个静态值作为索引的分区键,从而允许您对排序键执行 begin_with 操作并取回所有项目。