Search code examples
amazon-web-servicesgoamazon-dynamodb

How to declare a ValueBuilder object to be a StringSet when doing an UpdateItem in Dynamodb using gosdk?


NOTE: Might seem like a duplicate of this but it's different because I need to do this via golang while that is in JS.

I want to do the following operation in goSDK on a dynamodb item:

 UpdateExpression: 'ADD socialAccounts :socialAccountId',
 ExpressionAttributeValues: {
   ':socialAccountId': {
      'SS': [socialAccountId]
    }
 },

Typically how that works out in GoSDK is:

expression.Add(expression.Name("socialAccounts"), expression.Value([]string{"socialAccountId"}))

However the SDK is not taking the array of strings as a SS(StringSet) type, but instead as a L(List) type.

Logged Error:

Error: ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND

I'm unable to find any functionality in the docs that specify how to mention a type.

Can anyone help?
Why I want to do it this way:

  1. I want this to work even when the attribute socialAccounts does not exist.
  2. I don't want to use the SET opearation with list_append because that can introduce duplicate elements.

Solution

  • Use dynamodb.AttributeValue if you need to specify the type:

    package main
    
    import (
        "fmt"
    
        "github.com/aws/aws-sdk-go/aws"
        "github.com/aws/aws-sdk-go/service/dynamodb"
        "github.com/aws/aws-sdk-go/service/dynamodb/expression"
    )
    
    func main() {
        val := (&dynamodb.AttributeValue{}).SetSS(aws.StringSlice([]string{"socialAccountId"}))
        expression.Add(expression.Name("socialAccounts"), expression.Value(val))
    
        fmt.Printf("%s\n", val)
    }
    

    Output:

    {
      SS: ["socialAccountId"]
    }