[英]java delete all items in dynamodb
我試圖在 dynamodb 中刪除我表中的所有項目,但它不起作用。
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 是我的主分區鍵
n2 是我的主要排序鍵
從 DynamoDB 中刪除所有項目的最佳方法是刪除表並重新創建它。
否則,將使用大量讀取容量和寫入容量單位,這將花費您。
刪除並重新創建表是最好的方法。
序言:雖然掃描操作很昂貴,但我需要這個答案來初始化測試場景的表(低容量)。 該表是由另一個進程創建的,我需要該表上的測試場景,因此我無法刪除和重新創建該表。
答案:給定:
DynamoDbClient 數據庫
靜態字符串 TABLE_NAME
靜態字符串 HASH_KEY
靜態字符串 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()); } }
要首先從表中刪除所有項目,您需要對表執行掃描操作,這將導致掃描結果。 使用迭代器循環遍歷 sacnoutcome 和主鍵及其主鍵值。這將是從表中刪除所有項目的方法之一。 希望這段代碼對你有用。 謝謝
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.