1

When calling the DynamoDB deleteItem API, I am getting The provided key element does not match the schema error. After researching, I have found that this error occurs when you don't give the full primary key, (i.e the table has a range key but the API call does not specify it). However, in my case, the table has no range key, it has got only a hash key called pk.

Here is my code:

const dynamodbDocClient = new AWS.DynamoDB.DocumentClient({ logger: console });
socket.on('my-event', async (payload) => {
   await dynamodbDocClient.delete({
      TableName: 'MyTable',
      Key: { pk: payload.id },
    }).promise()
})

Can someone list all other cases where this error may occur?

Azamat Abdullaev
  • 726
  • 9
  • 24
  • 1
    Does this answer your question? [DynamoDB : The provided key element does not match the schema](https://stackoverflow.com/questions/25886403/dynamodb-the-provided-key-element-does-not-match-the-schema) – flaxon Sep 01 '21 at 20:26
  • It sounds like you aren't passing the key correctly to the query then. How about including your code in your question? – Mark B Sep 01 '21 at 20:45
  • 1
    @MarkB The only issue that may possibly happen with my query is that what I pass as a `pk` may be `undefined` sometimes. However, I tried to simulate this manually, but it gives a different error: "The number of conditions on the keys is invalid". I can't reproduce the same error message in the question anyways. – Azamat Abdullaev Sep 02 '21 at 09:27
  • @MarkB Included my code as well – Azamat Abdullaev Sep 02 '21 at 09:39
  • @MarkB No, it does not cause `The provided key element does not match the schema`, but it causes `The number of conditions on the keys is invalid`, which is not the same error. – Azamat Abdullaev Sep 02 '21 at 11:27
  • @MarkB Passing `Key: { }` also causes `The number of conditions on the keys is invalid`, which is again not the same error. – Azamat Abdullaev Sep 02 '21 at 11:29

2 Answers2

5

It's kinda hard to judge this without knowing your database-schema, but a possible problem could be that your primary key is defined as a number (eg. Integer or Long) in DynamoDB, but payload.id is of type String (or vice versa).

You could solve this by parsing payload.id to Javascripts integrated Number-Type.

Key: { pk: parseInt(payload.id) },

Conversely, if your Primary-Key is defined as a String and payload.id is of type Number:

// Convert the id to string
Key: { pk: payload.id + '' },
0

This happened to me (in Python boto3 though), in cases where I didn't pass the full DynamoDB JSON for key:

const dynamodbDocClient = new AWS.DynamoDB.DocumentClient({ logger: console });
socket.on('my-event', async (payload) => {
   await dynamodbDocClient.delete({
      TableName: 'MyTable',
      Key: { pk: {'S': payload.id }},
    }).promise()
})

Note: S is in case your ID is a string (GUID for example), and you would change it to the appropriate data type (N in case of number).

Caldazar
  • 2,801
  • 13
  • 21