DynamoDB: Delete All Items With Partition Key (Guide w/ Code Examples)
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.
Similar Code Examples
- DynamoDB: Delete
- DynamoDB: Delete Multiple Items in Javascript
- DynamoDB BatchWriteItem in Typescript
- DynamoDB: GetItem
- DynamoDB Get in Typescript
- DynamoDB: Query Group By
- DynamoDB: Not Begins With
- DynamoDB: Query KeyConditionExpression
- DynamoDB: Query Count
- DynamoDB: Get Table
- DynamoDB: BatchGetItem
- DynamoDB: Batch Get
- DynamoDB: Query Items
- DynamoDB: Not Between
- DynamoDB: Get Last 10 Records
Tired of switching accounts and regions? Use Dynobase.
Try 7-day free trial. No strings attached.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase