javascript - 如何使用 DynamoDB batchGet 命令
我按照发布在 AWS DynamoDB 教程中的内容创建了一个“Movie”DynamoDB 表
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.01.html
带有以下属性:
var tableAttrs = {
TableName : "Movies",
KeySchema: [
{ AttributeName: "year", KeyType: "HASH"},
{ AttributeName: "title", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "year", AttributeType: "N" },
{ AttributeName: "title", AttributeType: "S" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
};
现在我想使用 batchGet 命令:
var params = {
"RequestItems" : {
"Movies": {
"Keys" : [
{year : { "N" : "1000" } },
{year : { "N" : "1001" } }
]
}
}
}
并使用以下方式运行它:
let db = new DynamoDB.DocumentClient({ apiVersion: '2012-08-10' })
let result = db.batchGet(params).promise();
但是我收到错误:
ValidationException: The provided key element does not match the schema
为什么提供的 year 作为关键元素与架构不匹配?如何避免此错误并使其正常工作?
下面是显示表格键的截图:
答案#1
BatchGetItem:来自文档
BatchGetItem 操作返回来自一个或多个表的一个或多个项目的属性。您可以通过主键来标识所请求的项目。
我们必须指定整个主键,即分区键和排序键的组合。GetItem 也是如此。
批量获取:
const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.batchGet(
{
RequestItems: {
Movies: {
Keys: [
{ year: 1000, title: "one" },
{ year: 1000, title: "two" },
],
},
},
},
function (err, data) {
console.log("err", err, "data", JSON.stringify(data));
}
);
要仅通过分区键获取记录,我们可以使用查询。
查询:
const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.query(
{
TableName: "Movies",
KeyConditionExpression: "#year = :yearValue ",
ExpressionAttributeValues: {
":yearValue": 1000,
},
ExpressionAttributeNames: {
"#year": "year",
},
},
function (err, data) {
if (err) console.error(err);
else
console.log("dynamodb query succeeded:", JSON.stringify(data, null, 2));
}
);
