给定带有
user_id (partition key)
和 created_at (sort key)
的表格:
{
"user_id": {
"S": "..."
},
"created_at": {
"N": "...."
},
"bot_answer": {
"S": "..."
},
"question": {
"S": "..."
}
}
我的 lambda 接收来自 dynamodb 的插入事件:
{
"Records": [
{
....
"eventName": "INSERT",
....
"dynamodb": {
....
"Keys": {
"user_id": {
"S": "user123"
},
"created_at": {
"N": "1681218896790"
}
},
"NewImage": {
"question": {
"S": "What is the capital of USA?"
},
"user_id": {
"S": "user123"
},
"created_at": {
"N": "1681218896790"
},
"bot_answer": {
"S": ""
}
},
.....
"StreamViewType": "NEW_AND_OLD_IMAGES"
},
......
}
]
}
我尝试使用以下命令更新项目(来自执行日志):
{
TableName: 'chat_messages_tbl',
Key: {
user_id: { S: 'user123' },
created_at: { N: '1681218896790' }
},
UpdateExpression: 'SET bot_answer = :bot_answer',
ExpressionAttributeValues: { ':bot_answer': { S: 'Hello from bot!' } },
ReturnValues: 'UPDATED_NEW'
}
但是我明白了
ValidationException: The provided key element does not match the schema
// sample code from lambda (nodejs)
const dynamoDB = DynamoDBDocumentClient.from(dynamoDBClient)
const result = await dynamoDB.send(new UpdateCommand({
TableName: 'chat_messages_tbl',
Key: {
user_id: { S: 'user123' },
created_at: { N: '1681218896790' }
},
UpdateExpression: 'SET bot_answer = :bot_answer',
ExpressionAttributeValues: { ':bot_answer': { S: 'Hello from bot!' } },
ReturnValues: 'UPDATED_NEW'
}))
注意,因为
created_at
是number
,我也尝试在不带单引号的更新命令中发送它:
created_at: { N: 1681218896790 } // instead of { N : '1681218896790' }
谢谢,F。
使用
DynamoDBDocumentClient
时,应使用原生 JavaScript types
而不是 DynamoDB JSON
格式,并从键中删除 S
和 N
并将值作为原生类型传递。
示例:
const dynamoDB = DynamoDBDocumentClient.from(dynamoDBClient);
const result = await dynamoDB.send(new UpdateCommand({
TableName: 'chat_messages_tbl',
Key: {
user_id: 'user123', // No need to wrap in { S: '...' }
created_at: 1681218896790 // Pass as a JavaScript number, not as { N: '...' }
},
UpdateExpression: 'SET bot_answer = :bot_answer',
ExpressionAttributeValues: { ':bot_answer': 'Hello from bot!' }, // No need to wrap in { S: '...' }
ReturnValues: 'UPDATED_NEW'
}));