我是 AWS 的新手,我正在尝试通过 Lambda 更新 DynamoDB 中的项目属性。我已经在 Node.JS 和 Python 中尝试过代码,并且两次尝试都返回:
module initialization error: An error occurred (ValidationException) when calling the UpdateItem operation: The provided key element does not match the schema
为什么会这样?这是我的表信息:
- 表名:High_Holiday_Auctions
- 主分区键: Aliyah_ID(字符串)
- 主排序键: HighestBidder(字符串)
所以我在我的代码中同时使用了分区键和排序键,所以我无法弄清楚是什么导致了错误
Lambda 尝试使用 Python:
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('High_Holiday_Auctions')
AliyahID = "YK_MaftirHaftarah"
HighestBidder = "unclaimed"
response = table.update_item(
Key={
'AliyahID': AliyahID,
'HighestBidder': HighestBidder
},
UpdateExpression="set HighestBidder = :h, CurrentHighBid =:c,
LastHighestBidder=:l",
ExpressionAttributeValues={
':h': "Harry S Truman",
':c': "100",
':l': "unclaimed"
},
ReturnValues="UPDATED_NEW"
)
print("UpdateItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))
Lambda 尝试使用 Node.JS:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = function index(event, context, callback) {
var table = 'High_Holiday_Auctions';
var AliyahID = "YK_MaftirHaftarah";
var HighestBidder ="unclaimed"
//updaate item unconditinoally
var params ={
TableName:table,
Key:{
"AliyahID": AliyahID,
"HighestBidder": HighestBidder
},
UpdateExpression: "set HighestBidder =:h, CurrentHighBid =:c, LastHighestBidder=:l",
ExpressionAttributeValues:{
":h":"George Burdell",
":c": "1000",
":l": "moe syslak"
},
ReturnValues:"UPDATED_NEW"
};
console.log("Updating the item...");
docClient.update(params, function(err, data) {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
});
};
不能完全回答我的问题的类似现有问题:
请您参考如下方法:
除非您的表使用复合主键,否则您只需要使用 Key 字段中的主分区键来获取要更新的项目。
我的猜测是您尝试更新该项目的表配置了一个简单的主键。
