2 回答

TA貢獻1780條經驗 獲得超5個贊
對于 DynamoDB,如果您想刪除所有項目,最好的方法是刪除并重新創建表,因為使用 boto3,每頁的元素數限制為 1000 個。
使用 boto3 執行此操作的問題是昂貴的成本......每次刪除都是一個寫入請求。如果您不想支付不必要的費用(這是最好的方法),請刪除并重新創建:)
順便一提...
import boto3
def lambda_handler(event, context):
try:
flag = False
table_name = 'details'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
scan = table.scan()
while !flag:
with table.batch_writer() as batch:
for each in scan['Items']:
batch.delete_item(
Key={
'id': each['id']
}
)
flag = True
except Exception as e:
print (e)

TA貢獻1797條經驗 獲得超6個贊
由于編輯隊列已滿,我無法編輯已接受的答案。
查看代碼,它只掃描并刪除一次項目。
LastEvaluatedKey
這是使用密鑰來確定是否需要重新掃描的工作代碼。當掃描達到最大數據集大小限制 1 MB時,該鍵存在。
import boto3
def lambda_handler(event, context):
? ? ?try:
? ? ? ? ? table_name = 'details'
? ? ? ? ? dynamodb = boto3.resource('dynamodb')
? ? ? ? ? table = dynamodb.Table(table_name)
? ? ? ? ? flag = True
? ? ? ? ? while flag:
? ? ? ? ? ? ? ?scan = table.scan()
? ? ? ? ? ? ? ?print(f"Deleting {scan['ScannedCount']} records...")
? ? ? ? ? ? ? ?flag = 'LastEvaluatedKey' in scan and scan['LastEvaluatedKey']
? ? ? ? ? ? ? ?with table.batch_writer() as batch:
? ? ? ? ? ? ? ? ? ? for each in scan['Items']:
? ? ? ? ? ? ? ? ? ? ? ? ?batch.delete_item(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Key={
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?'id': each['id']
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ?)
? ? ?except Exception as e:
? ? ? ? ? print(e)
添加回答
舉報