在 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 表示那裡本來就沒有東西。 DeleteItem的ReturnValues只支援NONE(預設)與ALL_OLD—ALL_NEW/UPDATED_*選項屬於UpdateItem。- 條件式刪除 — 加上
ConditionExpression(例如以attribute_exists(Artist)讓缺少的項目失敗,或以值來守衛);失敗的條件會回傳*types.ConditionalCheckFailedException,以errors.As比對。 DeleteItem每次呼叫只移除一個項目。沒有「全部刪除」的 API — 若要清空表格,請以Scan逐一取得 key 並批次刪除,或刪掉並重建表格。
改用視覺化操作
以條件為刪除加上守衛?DynamoDB Expression Builder 會為你組裝 ConditionExpression 與 name/value map。
想在 GUI 中刪除項目 — 選取列、確認、完成,產生的程式碼一鍵可得 — 下載 DynoTable。
相關範例
- 在 Java 中使用 DynamoDB DeleteItem — 以 AWS SDK for Java 2.x 執行相同的刪除。
- 在 Go 中使用 DynamoDB PutItem — 同一個 key 的寫入端。
- DynamoDB 條件運算式 — 以
attribute_exists與值檢查為刪除加上守衛。 - DynamoDB ConditionalCheckFailedException — 失敗的條件式刪除會拋出什麼,以及何時屬預期之內。
References
- DeleteItem — Amazon DynamoDB API Reference
- Use DeleteItem with an AWS SDK or CLI — Amazon DynamoDB Developer Guide
- dynamodb package — AWS SDK for Go v2 (pkg.go.dev)
- dynamodb/types package — AWS SDK for Go v2 (pkg.go.dev)
- Condition expressions — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。