在 Go(AWS SDK v2)中使用 DynamoDB PutItem

PutItem 寫入整個項目,建立它、或取代任何具有相同 primary key 的既有項目。在 AWS SDK for Go v2 中,你以 dynamodb.PutItemInput 呼叫 client.PutItem,其 Item map 以來自 types 套件的帶型別值持有每個屬性。

Code

package main

import (
	"context"
	"errors"
	"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/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

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

	_, err = client.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String("Music"),
		Item: map[string]types.AttributeValue{
			"Artist":     &types.AttributeValueMemberS{Value: "Arturo Sandoval"},
			"SongTitle":  &types.AttributeValueMemberS{Value: "Cubano Chant"},
			"AlbumTitle": &types.AttributeValueMemberS{Value: "Danzon"},
			"Year":       &types.AttributeValueMemberN{Value: "1994"},
			"Awards":     &types.AttributeValueMemberN{Value: "0"},
		},
		ConditionExpression: aws.String("attribute_not_exists(#cond0) AND attribute_not_exists(#cond1)"),
		ExpressionAttributeNames: map[string]string{
			"#cond0": "Artist",
			"#cond1": "SongTitle",
		},
	})
	if err != nil {
		var ccf *types.ConditionalCheckFailedException
		if errors.As(err, &ccf) {
			fmt.Println("A song with that key already exists — not overwritten")
			return
		}
		log.Fatalf("put item: %v", err)
	}
	fmt.Println("Song written")
}

若要改從單純的 Go struct 建立 Item map,請使用 github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalueattributevalue.MarshalMap

說明

  • Item — 必須包含表格的完整 primary key,以及任何其他屬性。數字在 AttributeValueMemberN 中以字串表示({Value: "1994"})。
  • Put 會取代 — 沒有條件時,PutItem 會靜默覆寫任何具有相同 key 的既有項目。若只想改動少數屬性而不清掉其餘部分,請用 UpdateItem
  • ConditionExpression — 對 key 屬性使用 attribute_not_exists(...),讓寫入成為一個只建立的插入;若項目已存在,寫入會以 ConditionalCheckFailedException 失敗。這是 DynamoDB 的樂觀鎖基本手法。#cond0/#cond1 別名透過 ExpressionAttributeNames 解析為 Artist/SongTitle(保留字安全)。
  • errors.As — Go SDK 會包裝服務錯誤,因此請以 errors.As 比對帶型別的 *types.ConditionalCheckFailedException,切勿用字串比較。
  • 若要取回被覆寫的項目,請設定 ReturnValues: types.ReturnValueAllOld

改用視覺化操作

手寫條件式 put?DynamoDB Expression Builder 會組裝 ConditionExpression 並複製程式碼。

想在 GUI 中新增與編輯項目 — 每個屬性一個欄位、型別選擇器,以及複製為程式碼 — 下載 DynoTable

相關範例

References

最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。

不必透過主控台就能操作 DynamoDB

DynoTable 是一款快速的 DynamoDB 桌面用戶端 — 瀏覽表格、執行 SQL 風格的查詢,並在本機編輯項目。