luux
luux

Reputation: 71

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

Upvotes: 7

Views: 11409

Answers (4)

Vadym Ozarynskyi
Vadym Ozarynskyi

Reputation: 335

  • List item

Late to the party, but recently I needed the same for my integration tests. Since it's integration tests, I don't want to depend on implementation and wanted to delete all content of all tables. So basically I retrieve all table names. Then retrieve key schemas for each table. And scan through each and construct key by which we delete item. We need construction of keys since for one table we can have only partition key and for other we need sort key as well.

        val client = enhancedClientBuilder.build()

    runBlocking {
        client.listTables().await().tableNames().forEach { tableName ->
            val table = client.describeTable { it.tableName(tableName) }.await().table()

            client.scan { it.tableName(tableName) }.await().items().forEach { item ->
                val itemIdentifier = mutableMapOf<String, AttributeValue>()
                table.keySchema().forEach { keySchema ->
                    itemIdentifier[keySchema.attributeName()] = item[keySchema.attributeName()]!!
                }

                client.deleteItem {
                    it.tableName(tableName)
                    it.key(itemIdentifier)
                }.await()
            }
        }
    }

Upvotes: 0

Ron Tuffin
Ron Tuffin

Reputation: 54658

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());
         }
     }
    

Upvotes: 6

Bhargav
Bhargav

Reputation: 95

To delete all the items from the table first you need to perform scan operation over the table which will results you an scanoutcome. Using the iterator loop over the sacnoutcome with the primary key and it's primary key value.This will be one of the approach to delete all the items from the table. Hope that this code will work you. Thanks

Table table = dynamoDB.getTable(your_table);
ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();

while (iterator.hasNext()) {
    your_table.deleteItem("PrimaryKey", iterator.next().get("primary key value"));
}

//May be we can make it look generic by reading key schema first as below
String strPartitionKey = null;
String strSortKey = null;
TableDescription description = table.describe();
List<KeySchemaElement> schema = description.getKeySchema();
for (KeySchemaElement element : schema) {
    if (element.getKeyType().equalsIgnoreCase("HASH"))
        strPartitionKey = element.getAttributeName();
    if (element.getKeyType().equalsIgnoreCase("RANGE"))
        strSortKey = element.getAttributeName();
}

ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();
while (iterator.hasNext()) {
    Item next = iterator.next();
    if (strSortKey == null && strPartitionKey != null)
        table.deleteItem(strPartitionKey, next.get(strPartitionKey));
    else if (strPartitionKey != null && strSortKey != null)
        table.deleteItem(strPartitionKey, next.get(strPartitionKey), strSortKey, next.get(strSortKey));
}

Upvotes: 3

notionquest
notionquest

Reputation: 39226

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.

Upvotes: 4

Related Questions