LoginSignup
1
0

More than 3 years have passed since last update.

DynamoDBからすべてのレーコドを削除する

Last updated at Posted at 2019-08-06

テストように実行したバッチ処理にてDynamoDBに2万件以上のレーコドができてしまった。コンソールで削除するのも時間の無駄なので簡単lambdaにて削除しました。

こんなに簡単ですね!

import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1')
table = dynamodb.Table('my_table_name')

def deleteItem(hashKey, rangeKey):
    try:
        response = table.delete_item(
            Key={
                'my_hash': hashKey,
                'my_range': rangeKey
            }
        )
    except ClientError as e:
        raise
    else:
        print("DeleteItem succeeded:")

def lambda_handler(event, context):

    pe = "my_hash, my_range" #projection fields

    response = table.scan(
        ProjectionExpression=pe,
        )
    for i in response['Items']:
        hashKey = i["my_hash"]
        rangeKey = i["my_range"] 
        deleteItem(hashKey,rangeKey)

    while 'LastEvaluatedKey' in response:
        response = table.scan(
            ProjectionExpression=pe,
            ExclusiveStartKey=response['LastEvaluatedKey']
            )

        for i in response['Items']:
            hashKey = i["my_hash"]
            rangeKey = i["my_range"] 
            deleteItem(hashKey,rangeKey)


    return 'Successfully complete delete all items from table.'
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0