Created
January 24, 2018 07:48
-
-
Save doncicuto/5945ae05a89ab3b627dfdd50ba95d4a4 to your computer and use it in GitHub Desktop.
DynamoDB Tutorial Part 3 (Update an Item conditionally)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/dynamodb" | |
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" | |
) | |
func main() { | |
type MovieKey struct { | |
Year int `json:"year"` | |
Title string `json:"title"` | |
} | |
type MovieActorsCondition struct { | |
Actors int `json:":num"` | |
} | |
type MovieInfo struct { | |
Actors []string `json:"actors"` | |
} | |
type MovieInfoUpdated struct { | |
Info MovieInfo | |
} | |
config := &aws.Config{ | |
Region: aws.String("us-west-2"), | |
Endpoint: aws.String("http://localhost:8000"), | |
} | |
sess := session.Must(session.NewSession(config)) | |
svc := dynamodb.New(sess) | |
key, err := dynamodbattribute.MarshalMap(MovieKey{ | |
Year: 2015, | |
Title: "The Big New Movie", | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
condition, err := dynamodbattribute.MarshalMap(MovieActorsCondition{ | |
Actors: 3, | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
input := &dynamodb.UpdateItemInput{ | |
Key: key, | |
TableName: aws.String("Movies"), | |
UpdateExpression: aws.String("remove info.actors[0]"), | |
ConditionExpression: aws.String("size(info.actors) >= :num"), | |
ExpressionAttributeValues: condition, | |
ReturnValues: aws.String("UPDATED_NEW"), | |
} | |
result, err := svc.UpdateItem(input) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
updatedAttributes := MovieInfoUpdated{} | |
err = dynamodbattribute.UnmarshalMap(result.Attributes, &updatedAttributes) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
fmt.Println("Actors updated: ", updatedAttributes.Info.Actors) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment