delete_item
Learn how to delete items from DynamoDB tables using the AWS SDK for Python (Boto3). This guide provides code examples for removing specific records based on their keys.
DynamoDB Delete Item
This section demonstrates how to delete a specific item from a DynamoDB table using the AWS SDK for Python (Boto3). Deleting an item requires specifying the table name and the primary key of the item to be removed.
Understanding DynamoDB Item Deletion
DynamoDB is a NoSQL database service that stores data in tables. Each item in a table is uniquely identified by its primary key. To delete an item, you must provide its complete primary key. This operation is idempotent, meaning that if you attempt to delete an item that does not exist, the operation will succeed without error.
Python Code Example for Deleting an Item
The following Python code snippet uses Boto3 to connect to a local DynamoDB instance (or a remote one if configured) and delete an item from the 'gamescores' table. The item is identified by its composite primary key, consisting of 'event' and 'timestamp'.
import boto3
# Initialize a Boto3 session and client for DynamoDB
# Ensure you replace 'eu-west-1' with your actual region if not using a local endpoint
# For local testing, endpoint_url is crucial. For AWS, remove endpoint_url.
client = boto3.Session(region_name='eu-west-1').client(
'dynamodb',
aws_access_key_id='YOUR_ACCESS_KEY_ID', # Replace with your AWS Access Key ID or leave empty for default credentials
aws_secret_access_key='YOUR_SECRET_ACCESS_KEY', # Replace with your AWS Secret Access Key or leave empty
endpoint_url='http://localhost:4567' # Remove or comment out for AWS, use for local DynamoDB
)
# Define the primary key of the item to delete
# The structure of the key must match the table's primary key definition
item_key = {
'event': {'S': 'gaming_nationals_zaf'},
'timestamp': {'S': '2019-02-08T14:53'}
}
# Specify the table name from which to delete the item
table_name = 'gamescores'
try:
# Call the delete_item API to remove the item
response = client.delete_item(
Key=item_key,
TableName=table_name
)
print(f"Successfully deleted item from {table_name}:")
print(response)
except client.exceptions.ResourceNotFoundException:
print(f"Error: Table '{table_name}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Key Parameters for delete_item
TableName
This parameter is mandatory and specifies the name of the DynamoDB table from which to delete the item.
Key
This parameter is also mandatory. It's a map that contains the primary key attributes of the item to be deleted. The attribute names and types must match those defined for the table's primary key.
Best Practices for Deleting Items
- Use Primary Keys: Always use the complete primary key to identify the item for deletion.
- Error Handling: Implement robust error handling to manage potential issues like network errors, permission problems, or non-existent tables/items.
- Conditional Deletes: For more advanced scenarios, you can use the
ConditionExpression
parameter to delete an item only if certain conditions are met, preventing accidental data loss. - Local Secondary Indexes (LSI) and Global Secondary Indexes (GSI): Note that deleting an item from a table does not automatically delete corresponding items in its secondary indexes.