In this section, we will create a function to delete document information in the DynamoDB table by user ID and filename.
Open AWS Lambda console
Click Create function

Enter function name: delete_document

import json
import boto3
import os
client = boto3.resource('dynamodb')
def lambda_handler(event, context):
# TODO implement
table_name = os.environ['TABLE_NAME']
error = None
doc_pk = event['pathParameters']['id']
print("doc_pk ", doc_pk)
doc_sk = event['queryStringParameters']['file']
print("doc_sk ", doc_sk)
table = client.Table(table_name)
key = {
'user_id':doc_pk,
'file': doc_sk
}
try:
table.delete_item(Key = key)
except Exception as e:
error = e
except Exception as e:
error = e
if error is None:
message = 'delete document successful!'
else:
print(error)
message = 'delete document fail'
return {
'statusCode': 200,
'body': message,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
}

The above code gets the TABLE_NAME environment variable, the partition key, and the sort key provided by the user. It then executes the delete command for the item in the table based on those partition key and sort key values.

TABLE_NAME in the key field


{
"Effect": "Allow",
"Action": "dynamoDB:DeleteItem",
"Resource": "arn:aws:dynamodb:REGION:ACCOUNT_ID:table/Documents"
}
Replace REGION and ACCOUNT_ID with the region where you created the table and your account ID.

