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

DeleteItem 依項目的完整 primary key 移除單一項目。在 AWS SDK for Go v2 中,你以 dynamodb.DeleteItemInput 呼叫 client.DeleteItem;搭配 types.ReturnValueAllOld,回應會告訴你是否真的刪除了任何東西。

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/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)

	out, err := client.DeleteItem(ctx, &dynamodb.DeleteItemInput{
		TableName: aws.String("Music"),
		Key: map[string]types.AttributeValue{
			"Artist":    &types.AttributeValueMemberS{Value: "Arturo Sandoval"},
			"SongTitle": &types.AttributeValueMemberS{Value: "Cubano Chant"},
		},
		ReturnValues: types.ReturnValueAllOld,
	})
	if err != nil {
		log.Fatalf("delete item: %v", err)
	}

	if len(out.Attributes) == 0 {
		fmt.Println("No item with that key existed")
	} else {
		fmt.Println("Deleted:", out.Attributes)
	}
}

說明

  • Key — 必須包含每一個 primary-key 屬性:simple key 只需 partition key,composite key 則需 partition sort key。
  • Delete 具冪等性 — 刪除一個不存在的 key 仍算成功(無錯誤)。搭配 ReturnValues: types.ReturnValueAllOld,被刪除的項目會回到 out.Attributes空 map 表示那裡本來就沒有東西。
  • DeleteItemReturnValues 只支援 NONE(預設)與 ALL_OLDALL_NEW/UPDATED_* 選項屬於 UpdateItem
  • 條件式刪除 — 加上 ConditionExpression(例如以 attribute_exists(Artist) 讓缺少的項目失敗,或以值來守衛);失敗的條件會回傳 *types.ConditionalCheckFailedException,以 errors.As 比對。
  • DeleteItem 每次呼叫只移除一個項目。沒有「全部刪除」的 API — 若要清空表格,請以 Scan 逐一取得 key 並批次刪除,或刪掉並重建表格。

改用視覺化操作

以條件為刪除加上守衛?DynamoDB Expression Builder 會為你組裝 ConditionExpression 與 name/value map。

想在 GUI 中刪除項目 — 選取列、確認、完成,產生的程式碼一鍵可得 — 下載 DynoTable

相關範例

References

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

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

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