如何从DynamoDB的StringSet类型字段中删除指定字符串元素
错误原因
你遇到的报错本质是DynamoDB的DELETE操作针对StringSet类型字段时,要求传入的待删除值必须是同类型的集合,不能是单个字符串,同时要注意你使用的SDK客户端类型是否会自动做DynamoDB类型转换:
- 第一次报错
operand type: MAP:你手动给值加了SS类型标记,如果你用的是AWS.DynamoDB.DocumentClient(大部分场景默认用的简化客户端),它会自动处理类型映射,你手动加的{SS: xxx}会被当成普通Map对象识别,不符合要求 - 第二次报错
operand type: STRING:你直接传单个字符串,但DELETE操作要求传入集合类型,单个字符串不符合要求
正确实现代码
情况1:使用AWS.DynamoDB.DocumentClient(推荐)
这个客户端会自动把JS的Set类型映射为DynamoDB的StringSet,直接按以下写法即可:
function removeLecture(event){ const studentsPath = 'lectures[' + Number.parseInt(event.lecture_id) + '].students'; const params = { TableName: 'TableName', Key: { 'Key': key }, UpdateExpression: `DELETE ${studentsPath} :student`, ExpressionAttributeValues: { // 必须传入Set类型,即使只删一个元素 ':student': new Set([event.student]) }, ReturnValues : 'UPDATED_NEW' } return ddb.update(params).promise(); }
情况2:使用原生AWS.DynamoDB客户端
如果是用的原生底层客户端,需要明确指定类型,且SS对应的值必须是数组:
function removeLecture(event){ const studentsPath = 'lectures[' + Number.parseInt(event.lecture_id) + '].students'; const params = { TableName: 'TableName', Key: { 'Key': { S: key } // 注意原生客户端key也要指定类型 }, UpdateExpression: `DELETE ${studentsPath} :student`, ExpressionAttributeValues: { ':student': { // SS对应的值必须是数组,即使只有一个待删除元素 'SS': [event.student] } }, ReturnValues : 'UPDATED_NEW' } return ddb.update(params).promise(); }
核心注意点
- 对StringSet/NumberSet/BinarySet执行
DELETE操作时,传入的待删除值必须是同类型的集合,不能是单个元素 - 使用DocumentClient时不要手动加S/SS/M等类型标记,客户端会自动处理类型映射
内容的提问来源于stack exchange,提问作者Francesco
相关产品推荐
相关产品推荐

