AWS DynamoDB 更新项目命令出现 ValidationException:提供的关键元素与架构不匹配

问题描述 投票:0回答:1

给定带有

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。

node.js aws-lambda amazon-dynamodb
1个回答
0
投票

使用

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'
}));
© www.soinside.com 2019 - 2024. All rights reserved.