如何使用 DynamoDB batchGet 命令

How to use DynamoDB batchGet command

我从

上发布的 AWS DynamoDB 教程创建了一个“电影”DynamoDB table

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 作为关键元素与架构不匹配?如何避免此错误并使其正常工作?

下面是显示 table 键的屏幕截图:

BatchGetItem:来自文档

The BatchGetItem operation returns the attributes of one or more items from one or more tables. You identify requested items by primary key.

我们必须指定整个主键,即分区键和排序键的组合。 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));
  }
);