Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java delete all items in dynamodb

Im trying to delete all items in my table in dynamodb but it does not work.

    try {
        ScanRequest scanRequest = new ScanRequest().withTableName(table);
        ScanResult scanResult = null;

        do {
            if (Check.nonNull(scanResult)) {
                scanRequest.setExclusiveStartKey(scanResult.getLastEvaluatedKey());
            }

            scanResult = client.scan(scanRequest);

            scanResult.getItems().forEach((Item) -> {
                String n1 = Item.get("n1").toString();
                String n2 = tem.get("n2").toString();
                DeleteItemSpec spec = new DeleteItemSpec().withPrimaryKey("n1", n1, "n2", n2);
                dynamodb.getTable(table).deleteItem(spec);
            });
        } while (Check.nonNull(scanResult.getLastEvaluatedKey()));
    } catch (Exception e) {
        throw new BadRequestException(e);
    }

n1 is my Primary partition key

n2 is my Primary sort key

like image 329
luux Avatar asked Jul 20 '26 15:07

luux


2 Answers

PREAMBLE: While a scan operation is expensive, I was needing this answer for initialising a table for a test scenario (low volume). The table was being created by another process and I needed the test scenario on that table, I could therefore not delete and recreate the table.

ANSWER: given:

  • DynamoDbClient db

  • static String TABLE_NAME

  • static String HASH_KEY

  • static String SORT_KEY

     ScanIterable scanIterable = db.scanPaginator(ScanRequest.builder()
             .tableName(TABLE_NAME)
             .build());
     for(ScanResponse scanResponse:scanIterable){
         for( Map<String, AttributeValue> item: scanResponse.items()){
             Map<String,AttributeValue> deleteKey = new HashMap<>();
             deleteKey.put(HASH_KEY,item.get(HASH_KEY));
             deleteKey.put(SORT_KEY,item.get(SORT_KEY));
             db.deleteItem(DeleteItemRequest.builder()
                     .tableName(TRANSACTION_TABLE_NAME)
                     .key(deleteKey).build());
         }
     }
    
like image 94
Ron Tuffin Avatar answered Jul 23 '26 06:07

Ron Tuffin


The best approach to delete all the items from DynamoDB is to drop the table and recreate it.

Otherwise, there are lot of read capacity and write capacity units being used which will cost you.

Dropping and recreating the table is the best approach.

like image 43
notionquest Avatar answered Jul 23 '26 05:07

notionquest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!