Created
January 24, 2018 07:15
-
-
Save doncicuto/d623ec0e74bf6ea0db7c364d88507393 to your computer and use it in GitHub Desktop.
DynamoDB Tutorial Part 3 (Update an Item)
This file contains 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 MovieInfoUpdate struct { | |
Plot string `json:":p"` | |
Rating float64 `json:":r"` | |
Actors []string `json:":a"` | |
} | |
type MovieInfo struct { | |
Plot string `json:"plot"` | |
Rating float64 `json:"rating"` | |
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 | |
} | |
update, err := dynamodbattribute.MarshalMap(MovieInfoUpdate{ | |
Plot: "Everything happens all at once.", | |
Rating: 5.5, | |
Actors: []string{"Larry", "Moe", "Curly"}, | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
input := &dynamodb.UpdateItemInput{ | |
Key: key, | |
TableName: aws.String("Movies"), | |
UpdateExpression: aws.String("set info.rating = :r, info.plot=:p, info.actors=:a"), | |
ExpressionAttributeValues: update, | |
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("Updated plot: ", updatedAttributes.Info.Plot) | |
fmt.Println("Updated rating: ", updatedAttributes.Info.Rating) | |
fmt.Println("Updated actors: ", updatedAttributes.Info.Actors) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment