如何使用 python (boto3) 从 DynamoDB 中删除所有项目?
我正在尝试这样做:
scan = table.scan()
with table.batch_writer() as batch:
for each in scan['Items']:
batch.delete_item(Key=each)
但是给我这个错误:
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the BatchWriteItem operation: The provided key element does not match the schema
最佳答案
虽然我同意删除表并重新创建它的效率要高得多,但在某些情况下,例如许多 GSI 或触发器事件与一个表相关联,而您不想重新关联它们。下面的脚本将迭代扫描以处理大表(每次扫描调用将返回 1Mb 的键值)并使用批处理功能删除表中的所有项目。
import boto3
dynamo = boto3.resource('dynamodb')
def truncateTable(tableName):
table = dynamo.Table(tableName)
#get the table keys
tableKeyNames = [key.get("AttributeName") for key in table.key_schema]
#Only retrieve the keys for each item in the table (minimize data transfer)
projectionExpression = ", ".join('#' + key for key in tableKeyNames)
expressionAttrNames = {'#'+key: key for key in tableKeyNames}
counter = 0
page = table.scan(ProjectionExpression=projectionExpression, ExpressionAttributeNames=expressionAttrNames)
with table.batch_writer() as batch:
while page["Count"] > 0:
counter += page["Count"]
# Delete items in batches
for itemKeys in page["Items"]:
batch.delete_item(Key=itemKeys)
# Fetch the next page
if 'LastEvaluatedKey' in page:
page = table.scan(
ProjectionExpression=projectionExpression, ExpressionAttributeNames=expressionAttrNames,
ExclusiveStartKey=page['LastEvaluatedKey'])
else:
break
print(f"Deleted {counter}")
truncateTable("YOUR_TABLE_NAME")
关于python - 使用 Python 删除 DynamoDB 的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169952/