我有一个 AWS DynamoDb 表,
我有 user_id 作为索引或 GSI(user_id-index
),
我也有 product_type 作为索引或 GSI(prod_type-index
).
我正在尝试使用 KeyConditionExpression 来查询 DynamoDb 表,
但是我得到了一个 -
Validation Exception, with message:"Query key condition not supported" and statusCode: 400
ValidationException: Query key condition not supported\n at Request.extractError
我在表上有以下 Item 结构 -
{
"id": "12345f9f-f08c-45ae-986a-f1b5ac712345",
"user_id": 1234,
"prod_type": "OTHER"
}
以下是我用于查询表的 NodeJs 代码 -
let AWS = require('aws-sdk');
AWS.config.update({
region: 'us-east-1'
});
let connection = new AWS.DynamoDB.DocumentClient();
let table = "some_table";
let params = {
IndexName : "user_id-index",
ExpressionAttributeValues: {
":v1": {
N: 1234
},
":v2": {
S: "OTHER"
}
},
ExpressionAttributeNames: {
"#userId": "user_id",
"#prodType": "prod_type"
},
TableName: table,
KeyConditionExpression: "#userId = :v1 and #prodType = :v2"
};
connection.query(params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
引用文献 -
Dynamodb query error - Query key condition not supported
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.KeyConditions.html
最佳答案
根据文档 here , 问题是您的 ExpressionAttributeValues 值不正确。您需要提供变量和数据类型与值的映射。您需要提供这样的映射:
let params = {
IndexName : "user_id-index",
ExpressionAttributeValues: {
":v1": {
N: 1234
},
":v2": {
S: "OTHER"
}
},
TableName: table,
KeyConditionExpression: "user_id = :v1 and prod_type = :v2"
};
您需要根据文档指定数据类型。 S 用于字符串文字,N 用于数字等。您可以在上面的文档中找到详细信息。我还强烈建议您也使用 ExpressionAttributeNames。我发现它的效果更好,并且是此 SDK 的最佳实践。您需要替换您在 KeyConditionExpression 的映射中指定的变量,如下所示:
let params = {
IndexName : "user_id-index",
ExpressionAttributeValues: {
":v1": {
N: 1234
},
":v2": {
S: "OTHER"
}
},
ExpressionAttributeNames: {
"#userId": "user_id",
"#prodType": "prod_type"
}
TableName: table,
KeyConditionExpression: "#userId = :v1 and #prodType = :v2"
};
关于node.js - 如何使用 KeyConditionExpression 查询 AWS DynamoDb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051891/