How do I batch delete with DynamoDB?

Issue

I am getting an error that “The provided key element does not match the schema”. uuid is my primary partition key. I also have a primary sort key for version. I figured I can use batchWrite (docs) to delete all items with same uuid.

My ES6 code is as follows:

delete(uuid) {
  const promise = new Promise();
  const params = {
    RequestItems: {
      [this.TABLE]: [
        {
          DeleteRequest: {
            Key: { uuid: uuid }
          }
        }
      ]
    }
  };


  // this._client references the DocumentClient
  this._client.batchWrite(params, function(err, data) {
    if (err) {
      // this gets hit with error
      console.log(err);
      return promise.reject(err);
    }

    console.log(result);
    return promise.resolve(result);
  });

  return promise;
}

Not sure why it is erroring on the key that is the primary. I have seen posts about needing other indexes for times when I am searching by something that isn’t a key. But I don’t believe that’s the case here.

Solution

Here is the batch write delete request sample. This code has been tested and working fine. If you change this code for your requirement, it should work.

Table Definition:-

Bag – Table Name

bag – Hash Key

No partition key in ‘Bag’ table

Batch Write Code:-

var AWS = require("aws-sdk");

AWS.config.update({
    region : "us-west-2",
    endpoint : "http://localhost:8000"
});

var documentclient = new AWS.DynamoDB.DocumentClient();

var itemsArray = [];

var item1 = {
    DeleteRequest : {
        Key : {
            'bag' : 'b1'    
        }
    }
};

itemsArray.push(item1);

var item2 = {
    DeleteRequest : {
        Key : {
            'bag' : 'b2'    
        }
    }
};

itemsArray.push(item2);

var params = {
    RequestItems : {
        'Bag' : itemsArray
    }
};
documentclient.batchWrite(params, function(err, data) {
    if (err) {
        console.log('Batch delete unsuccessful ...');
        console.log(err, err.stack); // an error occurred
    } else {
        console.log('Batch delete successful ...');
        console.log(data); // successful response
    }

});

Output:-

Batch delete successful ...
{ UnprocessedItems: {} }

Answered By – notionquest

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.