Search code examples
aws-lambdaamazon-dynamodbboto

AWS DynamoDB Delete Item


I'm working on deleting DynamoDB item through Lambda.

I have a simple table setup and Partition key is Date (Number) and I don't have sort key. I tested below command in AWS CLI (via CMD) and it is working successfully.

aws dynamodb delete-item --table-name serverlessApp --key '{\"date\":{\"N\":\"123\"}}'

However, when I use below code in Lambda (Python 3.1.1), it shows the error.

table.delete_item(Key={"date":{"N":"123"}})

Also tested this, but not working..

table.delete_item(Key={"date":{"N":"123"}, "message":{"S":"test"}})

Do you have any idea? Here is DynamoDB JSON View and Error View.

{
  "date": {
    "N": "123"
  },
  "message": {
    "S": "test"
  }
}
{
  "errorMessage": "An error occurred (ValidationException) when calling the DeleteItem operation: The provided key element does not match the schema",
  "errorType": "ClientError",
  "requestId": "ba83cf56-7b36-4dc9-a5be-29efed41c78c",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 21, in lambda_handler\n    table.delete_item(Key={\"date\":{\"N\":\"123\"}})\n",
    "  File \"/var/lang/lib/python3.11/site-packages/boto3/resources/factory.py\", line 580, in do_action\n    response = action(self, *args, **kwargs)\n",
    "  File \"/var/lang/lib/python3.11/site-packages/boto3/resources/action.py\", line 88, in __call__\n    response = getattr(parent.meta.client, operation_name)(*args, **params)\n",
    "  File \"/var/lang/lib/python3.11/site-packages/botocore/client.py\", line 534, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    "  File \"/var/lang/lib/python3.11/site-packages/botocore/client.py\", line 976, in _make_api_call\n    raise error_class(parsed_response, operation_name)\n"
  ]
}

Solution

  • My assumption here is that you are using the higher level client, which is called Resource, in which the item parameters should not use DynamoDB Type Descriptors:

    table.delete_item(Key={"date": 123})
    

    Low Level

    dynamodb_client = boto3.client('dynamodb', region_name='us-west-2')
    

    High Level

    dynamodb_resource = boto3.resource('dynamodb', region_name='us-west-2')
    
    table = dynamodb_resource.Table('my-table')
    

    Deep Dive

    You can find out more on the differences between the high-level and low-level client here: https://aws.amazon.com/blogs/database/exploring-amazon-dynamodb-sdk-clients/