“The provided key element does not match the schema” error when getting an item from DynamoDB

℡╲_俬逩灬. 提交于 2020-02-26 06:22:47

问题


This is the table partition key setting

The table content

When I tried to get an item from the table, it prints this error

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the GetItem operation: The provided key element does not match the schema

This is my code

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('testDynamodb')
response = table.get_item(Key={'userId': "user2873"})
item = response['Item']
print(item)

Any ideas? thanks.


回答1:


Your table schema has both hash key and sort key defined. When using DynamoDB GetItem you must provide both of them, here is an excerpt from documentation

For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.

So given your example, here is how get_item parameters should look like:

response = table.get_item(Key={'userId': "user2873", 'createdAt': "1489376547"})



回答2:


One other thing that works is the following code below:

from boto3.dynamodb.conditions import Key

result = table.query(
        KeyConditionExpression=Key('userId').eq('user2873')
    )



回答3:


I guess you don't have to put all the related attributes

in my case I only have one PK as col

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
  const connectionId = event.requestContext.connectionId;
  deleteConnectionId(connectionId).then(() => {
    callback(null, { statusCode: 200 , message: 'userId deleted'});
  });
};


function deleteConnectionId(connectionId) {
  return ddb
    .delete({ TableName: 'your table name', 
        Key: {
            userId : connectionId.toString() // userId is my PK in this case
         }
    } )
    .promise();
}


来源:https://stackoverflow.com/questions/42757872/the-provided-key-element-does-not-match-the-schema-error-when-getting-an-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!