Created
January 24, 2018 07:31
-
-
Save doncicuto/fec0373b6f7eea14a28170664034dfb0 to your computer and use it in GitHub Desktop.
DynamoDB Tutorial Part 3 (Increment Atomic Counter)
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 MovieRatingInc struct { | |
Increment int `json:":val"` | |
} | |
type MovieInfo struct { | |
Rating float64 `json:"rating"` | |
} | |
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 | |
} | |
increment, err := dynamodbattribute.MarshalMap(MovieRatingInc{ | |
Increment: 1, | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
input := &dynamodb.UpdateItemInput{ | |
Key: key, | |
TableName: aws.String("Movies"), | |
UpdateExpression: aws.String("set info.rating = info.rating + :val"), | |
ExpressionAttributeValues: increment, | |
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 rating: ", updatedAttributes.Info.Rating) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment