BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: DynamoDB Get Item

Go 1.23

Retrieve a single item from an Amazon DynamoDB table using its primary key. This sample shows how to use `GetItem` and unmarshal the result back into a Go struct.

Code

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb"
    "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

type User struct {
    ID    string `dynamodbav:"id"`
    Name  string `dynamodbav:"name"`
    Email string `dynamodbav:"email"`
}

func main() {
    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"))
    if err != nil {
        log.Fatalf("unable to load SDK config, %v", err)
    }

    client := dynamodb.NewFromConfig(cfg)

    // Define the primary key of the item to retrieve
    key, err := attributevalue.MarshalMap(map[string]string{
        "id": "123",
    })
    if err != nil {
        log.Fatalf("failed to marshal key, %v", err)
    }

    // Retrieve the item
    result, err := client.GetItem(context.TODO(), &dynamodb.GetItemInput{
        TableName: aws.String("Users"),
        Key:       key,
    })
    if err != nil {
        log.Fatalf("failed to get item, %v", err)
    }

    if result.Item == nil {
        fmt.Println("Item not found")
        return
    }

    // Unmarshal the item into a struct
    var user User
    err = attributevalue.UnmarshalMap(result.Item, &user)
    if err != nil {
        log.Fatalf("failed to unmarshal item, %v", err)
    }

    fmt.Printf("Found user: %s (%s)\n", user.Name, user.Email)
}

Explanation

Retrieving data from DynamoDB by its primary key is done using the GetItem operation. This is the most efficient way to access a single record, as it provides direct access without scanning the table. The AWS SDK for Go v2 requires you to provide the key as a map of attribute values, which identifies the unique item you want to fetch.

Once the item is retrieved, the SDK returns it as a map[string]types.AttributeValue. To work with this data in your Go application, you typically want to convert it back into a strongly-typed struct. The attributevalue.UnmarshalMap helper function performs this reverse transformation, mapping the DynamoDB attributes back to your struct fields based on the dynamodbav tags.

It is important to handle the case where the item does not exist. In DynamoDB, a successful GetItem request for a non-existent key does not return an error; instead, it returns a result with a nil Item field. Your code should explicitly check for this condition to avoid null pointer exceptions or logic errors.

  • Key Construction: Use attributevalue.MarshalMap to easily create the primary key map from a Go map or struct.
  • Nil Check: Always check if result.Item is nil to determine if the record was found.
  • Unmarshaling: Use attributevalue.UnmarshalMap to decode the raw DynamoDB response into a usable Go struct.

Code Breakdown

29
Constructing the key. We use attributevalue.MarshalMap to convert a simple Go map {"id": "123"} into the complex DynamoDB JSON format required for the Key parameter.
37
client.GetItem performs the lookup. It takes the context, table name, and the key we constructed. This operation is strongly consistent by default if you set ConsistentRead to true, otherwise it's eventually consistent.
45
Checking for existence. If no item matches the key, DynamoDB returns a success response (err is nil) but result.Item is nil. This check is mandatory.
52
attributevalue.UnmarshalMap(result.Item, &user) populates the "user" struct with data from the database response. It matches fields based on the "dynamodbav" tags defined in the struct.