DynamoDB: Delete All Items With Partition Key (Guide w/ Code Examples)

Rafal Wilinski

Provided by Rafal Wilinski

You need to follow the below steps to delete all items with a specific partition key using the AWS JavaScript SDK.

  • First, you need to use the query method to retrieve all items with that key.
  • Then you can use the batchWrite method to delete them.

Here is an example of how to do this:

const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); const partitionKey = "some-partition-key-value"; const tableName = "my-table-name"; // Use the query method to retrieve all items with the specified partition key dynamoDb.query({ TableName: tableName, KeyConditionExpression: "partitionKey = :pk", ExpressionAttributeValues: { ":pk": partitionKey } }, (err, data) => { if (err) { console.error("Error querying DynamoDB:", err); } else { // Extract the items from the query result const items = data.Items; // Use the batchWrite method to delete the items dynamoDb.batchWrite({ RequestItems: { [tableName]: items.map(item => ({ DeleteRequest: { Key: { partitionKey: item.partitionKey, sortKey: item.sortKey } } })) } }, (err) => { if (err) { console.error("Error deleting items from DynamoDB:", err); } else { console.log("Successfully deleted items with partition key", partitionKey); } }); } });

Note that this example assumes that your table has a partition key named partitionKey and a sort key named sortKey. If your table has different key names, you must adjust the code accordingly.

Better DynamoDB experience.

Start your 7-day free trial today

Product Features

Member Portal
© 2024 Dynobase
Using DynamoDB Console frequently?
Try Dynobase to accelerate your DynamoDB workflow. Start your 7-day free trial today.