In this blog, we will learn how to delete items in DynamoDB using python and boto3. In DynamoDB, we can only delete one single item at a time.

Delete Item in DynamoDB

When we want to delete an item in the DynamoDB table, we have to pass the item’s full primary key in the function call.

import boto3
from pprint import pprint

boto3.setup_default_session(profile_name="ah")

table_name = "orders"
dynamodb_resource = boto3.resource("dynamodb")
orders_table = dynamodb_resource.Table(table_name)


def delete_item():
    response = orders_table.delete_item(
        Key={
            "order_id": "ord100",
            "order_date": "2022-07-01",
        }
    )

    pprint(response)

The above code deletes an item in the DynamoDB table with an order_id of ‘ord100’ and order_date of ‘2022-07-01’.

Deleting DynamoDB Item with Condition

We can also use DynamoDB delete API to delete an item only when some condition is true. Consider, for example, we want to delete an order only if it has an item count of 0. We can achieve that using the below code.

def delete_item_with_condition():
    response = orders_table.delete_item(
        Key={
            "order_id": "ord100",
            "order_date": "2022-07-01",
        },
        ConditionExpression="item_count = :v",
        ExpressionAttributeValues={
            ":v": 0,
        },
    )

    pprint(response)

The above code will only delete this item if the item_count for this order is 0. If item_count is not 0, then the code throws the following exception.

botocore.errorfactory.ConditionalCheckFailedException: An error occurred
(ConditionalCheckFailedException) when calling the DeleteItem operation: The conditional request failed

Delete Multiple Items in DynamoDB Table using Python

DynamoDB delete API does not support deleting multiple items in a single call. But we can use BatchDelete API to delete multiple items in the DynamoDB table. I will soon be publishing a blog about it, so stay tuned. See you in the next blog.

Similar Posts