Python 从 DynamoDB 获取项目时出现“提供的关键元素与架构不匹配”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42757872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"The provided key element does not match the schema" error when getting an item from DynamoDB
提问by Keoros
This is the table partition key setting
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
botocore.exceptions.ClientError: 调用 GetItem 操作时发生错误 (ValidationException):提供的关键元素与架构不匹配
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.
有任何想法吗?谢谢。
回答by xtx
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
您的表架构同时定义了哈希键和排序键。使用 DynamoDB GetItem 时,您必须同时提供它们,这里是文档摘录
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:
因此,以您的示例为例,get_item 参数应如下所示:
response = table.get_item(Key={'userId': "user2873", 'createdAt': "1489376547"})
回答by user754036
One other thing that works is the following code below:
另一件有效的事情是下面的代码:
from boto3.dynamodb.conditions import Key
result = table.query(
KeyConditionExpression=Key('userId').eq('user2873')
)
回答by Hasoun GH
I guess you don't have to put all the related attributes
我想你不必把所有相关的属性
in my case I only have one PK as col
就我而言,我只有一个 PK 作为 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();
}