【问题标题】:Delete DynamoDB string attribute with golang expression package使用 golang 表达式包删除 DynamoDB 字符串属性
【发布时间】:2020-04-30 03:34:43
【问题描述】:

我在使用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 = :1\n"
}

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

【问题讨论】:

    标签: go amazon-dynamodb aws-sdk


    【解决方案1】:

    原来我需要使用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, #1\n"
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2023-01-18
      • 1970-01-01
      • 2011-05-13
      • 2022-11-15
      • 2018-01-26
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多