UpdateItem with many attributes

Viewed 889

I am trying to update an item which has many attributes (more than 100). I can see there are two ways to update this item.

PutItem: PutItem can update the item, as per my understanding I need to send all the 100 attributes for each request because I am using struct for marshaling and unmarshaling the request data. If I skip any field default value will be inserted into table.

UpdateItemInput: We can update table using UpdateItemInput as follows -

    svc := dynamodb.New(session.New())
    input := &dynamodb.UpdateItemInput{
    ExpressionAttributeNames: map[string]*string{
        "#AT": aws.String("AlbumTitle"),
        "#Y":  aws.String("Year"),
    },
    ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
        ":t": {
            S: aws.String("Louder Than Ever"),
        },
        ":y": {
            N: aws.String("2015"),
        },
    },
    Key: map[string]*dynamodb.AttributeValue{
        "Artist": {
            S: aws.String("Acme Band"),
        },
        "SongTitle": {
            S: aws.String("Happy Day"),
        },
    },
    ReturnValues:     aws.String("ALL_NEW"),
    TableName:        aws.String("Music"),
    UpdateExpression: aws.String("SET #Y = :y, #AT = :t"),
}

result, err := svc.UpdateItem(input)

Here we need to write ExpressionAttributeNames for many attributes, and if attributes to be updated are dynamic how should I handle this.

I am not sure which is the efficient way to handle update. Please suggest which is the better way OR there is any other way to handle this situation.

1 Answers

You are right that a PutItem replaces any existing item that has the same key, so if you want to only merge a bunch of new attribute values into an existing item, you need to use UpdateItem.

One option is indeed, as you said, to use the UpdateExpression syntax. You'll need to create a string like SET #a1 = :a1, SET #a2 = :a2, ... and also all set these a1 etc., but that's not such a hard programming exercise.

Another option is instead of UpdateExpression, use the older AttributeUpdates syntax, with a bunch of PUT operations. This is perhaps slightly easier (you only build one JSON list instead of an expression plus two lists) but both really require a bit of simple programming.

Related