使用golang表达式包删除DynamoDB字符串属性



使用UpdateItem命令删除dynamodb项的属性时遇到问题:https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/expression/#Builder.WithUpdate

expr := expression.Set(
expression.Name("my_attribute_a"),
expression.Value(""),
).Set(
expression.Name("my_attribute_b"),
expression.Value(""),
)
update, err := expression.NewBuilder().
WithUpdate(expr).
Build()
if err != nil {
return fmt.Errorf("failed to build update expression: %v", err)
}
input := &dynamodb.UpdateItemInput{
TableName:                 &ddb.emailAccountTableName,
ExpressionAttributeNames:  update.Names(),
ExpressionAttributeValues: update.Values(),
Key: map[string]*dynamodb.AttributeValue{
"id": {
S: &id,
},
},
UpdateExpression:       update.Update(),
ReturnConsumedCapacity: aws.String(dynamodb.ReturnConsumedCapacityTotal),
}
fmt.Println(input.String())
result, err := ddb.svc.UpdateItem(input)

运行以上操作的结果是:

{
ExpressionAttributeNames: {
#1: "my_attribute_a",
#0: "my_attribute_b"
},
ExpressionAttributeValues: {
:0: {
NULL: true
},
:1: {
NULL: true
}
},
Key: {
id: {
S: "38zqtaNezbB8eZw4pbJKm7"
}
},
ReturnConsumedCapacity: "TOTAL",
TableName: "my-table",
UpdateExpression: "SET #0 = :0, #1 = :1n"
}

结果是项目的属性被设置为true。我希望删除这些属性。我尝试过使用nil,但结果相同,expression.Null只是将字符串设置为值NULL

原来我需要使用expression.Remove而不是expression.Set,下面是相关的更新:

expr := expression.Remove(
expression.Name("my_attribute_a"),
).Remove(
expression.Name("my_attribute_b"),
)
update, err := expression.NewBuilder().
WithUpdate(expr).
Build()

结果如下:

{
ExpressionAttributeNames: {
#0: "my_attribute_a",
#1: "my_attribute_b
},
Key: {
id: {
S: "qfsphqt37ELyn2BanwE2fd"
}
},
ReturnConsumedCapacity: "TOTAL",
TableName: "my-table",
UpdateExpression: "REMOVE #0, #1n"
}

最新更新