DynamoDb: Delete all items having same Hash Key

Consider the following table:

Table (documentId : Hash Key, userId: Range Key)

How can I write a code to delete all the items having the same documentId and preferably without retrieving the items.

3 Answers

Currently, You cannot delete all the items just by passing the Hash key, to delete an item it requires Hash + Range because that's what makes it unique.

You have to know both your (hash + range) to delete the item. 

Edit: Here is the reference link from DynamoDB documentation

Please read the explanation of the "KEY" which clearly says that we must pass both Hash (Partition Key) and Range (Sort Key) to delete the item.

4

If you want to delete only by hash key, you need to query records first and then use batchDelete to delete all the records.

HashMap<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":v1", new AttributeValue().withS(value));
DynamoDBQueryExpression<DocumentTable> queryExpression = new DynamoDBQueryExpression<DocumentTable>() .withKeyConditionExpression("documentId = :v1") .withExpressionAttributeValues(eav);
List<DocumentTable> ddbResults = dynamoDBMapper.query(DocumentTable.class, queryExpression);
dynamoDBMapper.batchDelete(ddbResults);

I would like to call out here that deleteItem deletes only one item at a time and both hash key and range key needs to be specified for this.

I have a similar requirement where I need to delete more than 10 million of rows from DynamoDB table. I was hoping that there would be a way to delete all the items based on a specific partition key but unfortunately there is no way (atleast I couldn't find).

It's painful to specify the specific values of hashkey and sortKey. The only option is to scan the table to retrieve primary key (or composite key) and then iterate over it to delete a single item using deleteItem API.

You can delete upto 25 items ( as large as 400KB) in a single call using BatchWriteItem API.

You can refer to this API from AWS for more information :

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like