python - 使用 Python 删除 DynamoDB 的所有项目

标签 python amazon-dynamodb boto3

如何使用 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/

相关文章:

python - 如何使用pysftp检查SFTP中是否存在文件?

amazon-web-services - Appsync Resolver UpdateItem 忽略空参数?

Python:按键、值比较两个相同的字典

java - DynamoDBMappingException : no HASH key value present

amazon-s3 - Amazon Elastic MapReduce - 从 S3 到 DynamoDB 的大量插入非常慢

amazon-s3 - 使用 boto3 删除 AWS S3 存储桶 - AttributeError

python - 如何使用 boto3 客户端删除仍然可用的 HIT

Python Boto3 'StreamingBody' 对象没有属性 'iter_lines'

python - 使用坐标 python 列表的广度优先搜索

python - python记录器的子项可以被删除吗?