Skip to content
Advertisement

How to use DynamoDB batchGet command

I created a “Movie” DynamoDB table from AWS DynamoDB tutorial posted at

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.01.html

with the attribute below:

    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
        }
    };

Now I want to use the batchGet command:

var params = {
  "RequestItems" : {
      "Movies": {
        "Keys" : [
          {year : { "N" : "1000" } },
          {year : { "N" : "1001" } }
        ]
      }
    }
}

And running it with:

let db = new DynamoDB.DocumentClient({ apiVersion: '2012-08-10' })

let result = db.batchGet(params).promise();

But I am getting the error:

ValidationException: The provided key element does not match the schema

Why does the provided year as a key element does not match the schema? How to avoid this error and make it work?

Below is the screenshot showing the table keys:

enter image description here

Advertisement

Answer

BatchGetItem : From the Docs

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

We must specify entire primary key i.e combination of partition key and sort key. Same with GetItem too.

Batch Get:

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));
  }
);

To get by records only by Partition Key, we can use query.

Query:

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));
  }
);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement