DynamoDB テーブルで項目を削除する - Amazon DynamoDB

DynamoDB テーブルで項目を削除する

AWS Management Console、AWS CLI、または AWS SDK を使用して、DynamoDB テーブルから項目を削除できます。項目の詳細については、「Amazon DynamoDB のコアコンポーネント」を参照してください。

AWS SDK を使用して DynamoDB テーブルで項目を削除する

次のコード例は、AWS SDK を使用して DynamoDB テーブルで項目を削除する方法を示しています。

.NET
AWS SDK for .NET
注記

GitHub には、その他のリソースもあります。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

/// <summary> /// Deletes a single item from a DynamoDB table. /// </summary> /// <param name="client">The initialized DynamoDB client object.</param> /// <param name="tableName">The name of the table from which the item /// will be deleted.</param> /// <param name="movieToDelete">A movie object containing the title and /// year of the movie to delete.</param> /// <returns>A Boolean value indicating the success or failure of the /// delete operation.</returns> public static async Task<bool> DeleteItemAsync( AmazonDynamoDBClient client, string tableName, Movie movieToDelete) { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = movieToDelete.Title }, ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() }, }; var request = new DeleteItemRequest { TableName = tableName, Key = key, }; var response = await client.DeleteItemAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • API の詳細については、「AWS SDK for .NET API リファレンス」の「DeleteItem」を参照してください。

Bash
Bash スクリプトを使用した AWS CLI
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

############################################################################## # function dynamodb_delete_item # # This function deletes an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_delete_item() { local table_name keys response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_delete_item" echo "Delete an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to delete." echo "" } while getopts "n:k:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " keys: $keys" iecho "" response=$(aws dynamodb delete-item \ --table-name "$table_name" \ --key file://"$keys") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-item operation failed.$response" return 1 fi return 0 }

この例で使用されているユーティリティ関数。

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • API の詳細については、AWS CLI コマンドリファレンスの「DeleteItem」を参照してください。

C++
SDK for C++
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

//! Delete an item from an Amazon DynamoDB table. /*! \sa deleteItem() \param tableName: The table name. \param partitionKey: The partition key. \param partitionValue: The value for the partition key. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::DynamoDB::deleteItem(const Aws::String &tableName, const Aws::String &partitionKey, const Aws::String &partitionValue, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration); Aws::DynamoDB::Model::DeleteItemRequest request; request.AddKey(partitionKey, Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue)); request.SetTableName(tableName); const Aws::DynamoDB::Model::DeleteItemOutcome &outcome = dynamoClient.DeleteItem( request); if (outcome.IsSuccess()) { std::cout << "Item \"" << partitionValue << "\" deleted!" << std::endl; } else { std::cerr << "Failed to delete item: " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • API の詳細については、「AWS SDK for C++ API リファレンス」の「DeleteItem」を参照してください。

CLI
AWS CLI

例 1: 項目を削除するには

次の delete-item の例は、MusicCollection テーブルから項目を削除し、削除した項目とそのリクエストで使用された容量に関する詳細を取得します。

aws dynamodb delete-item \ --table-name MusicCollection \ --key file://key.json \ --return-values ALL_OLD \ --return-consumed-capacity TOTAL \ --return-item-collection-metrics SIZE

key.json の内容:

{ "Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Scared of My Shadow"} }

出力:

{ "Attributes": { "AlbumTitle": { "S": "Blue Sky Blues" }, "Artist": { "S": "No One You Know" }, "SongTitle": { "S": "Scared of My Shadow" } }, "ConsumedCapacity": { "TableName": "MusicCollection", "CapacityUnits": 2.0 }, "ItemCollectionMetrics": { "ItemCollectionKey": { "Artist": { "S": "No One You Know" } }, "SizeEstimateRangeGB": [ 0.0, 1.0 ] } }

詳細については、「Amazon DynamoDB ディベロッパーガイド」の「項目を書き込みます」を参照してください。

例 2: 条件付きで項目を削除するには

次の例では、ProductCategorySporting Goods または Gardening Supplies で、その価格が 500 および 600 の場合のみ、ProductCatalog テーブルから項目を削除します。削除された項目に関する詳細が返されます。

aws dynamodb delete-item \ --table-name ProductCatalog \ --key '{"Id":{"N":"456"}}' \ --condition-expression "(ProductCategory IN (:cat1, :cat2)) and (#P between :lo and :hi)" \ --expression-attribute-names file://names.json \ --expression-attribute-values file://values.json \ --return-values ALL_OLD

names.json の内容:

{ "#P": "Price" }

values.json の内容:

{ ":cat1": {"S": "Sporting Goods"}, ":cat2": {"S": "Gardening Supplies"}, ":lo": {"N": "500"}, ":hi": {"N": "600"} }

出力:

{ "Attributes": { "Id": { "N": "456" }, "Price": { "N": "550" }, "ProductCategory": { "S": "Sporting Goods" } } }

詳細については、「Amazon DynamoDB ディベロッパーガイド」の「項目を書き込みます」を参照してください。

  • API の詳細については、AWS CLI コマンドリファレンスの「DeleteItem」を参照してください。

Go
SDK for Go V2
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples. // It contains a DynamoDB service client that is used to act on the specified table. type TableBasics struct { DynamoDbClient *dynamodb.Client TableName string } // DeleteMovie removes a movie from the DynamoDB table. func (basics TableBasics) DeleteMovie(movie Movie) error { _, err := basics.DynamoDbClient.DeleteItem(context.TODO(), &dynamodb.DeleteItemInput{ TableName: aws.String(basics.TableName), Key: movie.GetKey(), }) if err != nil { log.Printf("Couldn't delete %v from the table. Here's why: %v\n", movie.Title, err) } return err } // Movie encapsulates data about a movie. Title and Year are the composite primary key // of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key, // and Info is additional data. type Movie struct { Title string `dynamodbav:"title"` Year int `dynamodbav:"year"` Info map[string]interface{} `dynamodbav:"info"` } // GetKey returns the composite primary key of the movie in a format that can be // sent to DynamoDB. func (movie Movie) GetKey() map[string]types.AttributeValue { title, err := attributevalue.Marshal(movie.Title) if err != nil { panic(err) } year, err := attributevalue.Marshal(movie.Year) if err != nil { panic(err) } return map[string]types.AttributeValue{"title": title, "year": year} } // String returns the title, year, rating, and plot of a movie, formatted for the example. func (movie Movie) String() string { return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n", movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"]) }
  • API の詳細については、「AWS SDK for Go API リファレンス」の「DeleteItem」を参照してください。

Java
SDK for Java 2.x
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteItem { public static void main(String[] args) { final String usage = """ Usage: <tableName> <key> <keyval> Where: tableName - The Amazon DynamoDB table to delete the item from (for example, Music3). key - The key used in the Amazon DynamoDB table (for example, Artist).\s keyval - The key value that represents the item to delete (for example, Famous Band). """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String key = args[1]; String keyVal = args[2]; System.out.format("Deleting item \"%s\" from %s\n", keyVal, tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build(); deleteDynamoDBItem(ddb, tableName, key, keyVal); ddb.close(); } public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put(key, AttributeValue.builder() .s(keyVal) .build()); DeleteItemRequest deleteReq = DeleteItemRequest.builder() .tableName(tableName) .key(keyToGet) .build(); try { ddb.deleteItem(deleteReq); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「DeleteItem」を参照してください。

JavaScript
SDK for JavaScript (v3)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「DeleteCommand」を参照してください。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, DeleteCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new DeleteCommand({ TableName: "Sodas", Key: { Flavor: "Cola", }, }); const response = await docClient.send(command); console.log(response); return response; };
SDK for JavaScript (v2)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

テーブルから項目を削除します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Key: { KEY_NAME: { N: "VALUE" }, }, }; // Call DynamoDB to delete the item from the table ddb.deleteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

DynamoDB ドキュメントクライアントを使用して、テーブルから項目を削除します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { Key: { HASH_KEY: VALUE, }, TableName: "TABLE", }; docClient.delete(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Kotlin
SDK for Kotlin
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

suspend fun deleteDynamoDBItem(tableNameVal: String, keyName: String, keyVal: String) { val keyToGet = mutableMapOf<String, AttributeValue>() keyToGet[keyName] = AttributeValue.S(keyVal) val request = DeleteItemRequest { tableName = tableNameVal key = keyToGet } DynamoDbClient { region = "us-east-1" }.use { ddb -> ddb.deleteItem(request) println("Item with key matching $keyVal was deleted") } }
  • API の詳細については、「AWS SDK for Kotlin API リファレンス」の「DeleteItem」を参照してください。

PHP
SDK for PHP
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

$key = [ 'Item' => [ 'title' => [ 'S' => $movieName, ], 'year' => [ 'N' => $movieYear, ], ] ]; $service->deleteItemByKey($tableName, $key); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; public function deleteItemByKey(string $tableName, array $key) { $this->dynamoDbClient->deleteItem([ 'Key' => $key['Item'], 'TableName' => $tableName, ]); }
  • API の詳細については、「AWS SDK for PHP API リファレンス」の「DeleteItem」を参照してください。

PowerShell
Tools for PowerShell

例 1: 指定されたキーと一致する DynamoDB 項目を削除します。

$key = @{ SongTitle = 'Somewhere Down The Road' Artist = 'No One You Know' } | ConvertTo-DDBItem

出力:

Remove-DDBItem -TableName 'Music' -Key $key -Confirm:$false
  • API の詳細については、「AWS Tools for PowerShell Cmdlet Reference」の「DeleteItem」を参照してください。

Python
SDK for Python (Boto3)
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class Movies: """Encapsulates an Amazon DynamoDB table of movie data.""" def __init__(self, dyn_resource): """ :param dyn_resource: A Boto3 DynamoDB resource. """ self.dyn_resource = dyn_resource # The table variable is set during the scenario in the call to # 'exists' if the table exists. Otherwise, it is set by 'create_table'. self.table = None def delete_movie(self, title, year): """ Deletes a movie from the table. :param title: The title of the movie to delete. :param year: The release year of the movie to delete. """ try: self.table.delete_item(Key={"year": year, "title": title}) except ClientError as err: logger.error( "Couldn't delete movie %s. Here's why: %s: %s", title, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise

項目が特定の条件を満たす場合にのみ削除されるように条件を指定できます。

class UpdateQueryWrapper: def __init__(self, table): self.table = table def delete_underrated_movie(self, title, year, rating): """ Deletes a movie only if it is rated below a specified value. By using a condition expression in a delete operation, you can specify that an item is deleted only when it meets certain criteria. :param title: The title of the movie to delete. :param year: The release year of the movie to delete. :param rating: The rating threshold to check before deleting the movie. """ try: self.table.delete_item( Key={"year": year, "title": title}, ConditionExpression="info.rating <= :val", ExpressionAttributeValues={":val": Decimal(str(rating))}, ) except ClientError as err: if err.response["Error"]["Code"] == "ConditionalCheckFailedException": logger.warning( "Didn't delete %s because its rating is greater than %s.", title, rating, ) else: logger.error( "Couldn't delete movie %s. Here's why: %s: %s", title, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「DeleteItem」を参照してください。

Ruby
SDK for Ruby
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

class DynamoDBBasics attr_reader :dynamo_resource attr_reader :table def initialize(table_name) client = Aws::DynamoDB::Client.new(region: "us-east-1") @dynamo_resource = Aws::DynamoDB::Resource.new(client: client) @table = @dynamo_resource.table(table_name) end # Deletes a movie from the table. # # @param title [String] The title of the movie to delete. # @param year [Integer] The release year of the movie to delete. def delete_item(title, year) @table.delete_item(key: {"year" => year, "title" => title}) rescue Aws::DynamoDB::Errors::ServiceError => e puts("Couldn't delete movie #{title}. Here's why:") puts("\t#{e.code}: #{e.message}") raise end
  • API の詳細については、「AWS SDK for Ruby API リファレンス」の「DeleteItem」を参照してください。

Rust
SDK for Rust
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

pub async fn delete_item( client: &Client, table: &str, key: &str, value: &str, ) -> Result<DeleteItemOutput, Error> { match client .delete_item() .table_name(table) .key(key, AttributeValue::S(value.into())) .send() .await { Ok(out) => { println!("Deleted item from table"); Ok(out) } Err(e) => Err(Error::unhandled(e)), } }
  • API の詳細については、「AWS SDK for Rust API リファレンス」の「DeleteItem」を参照してください。

SAP ABAP
SDK for SAP ABAP
注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

TRY. DATA(lo_resp) = lo_dyn->deleteitem( iv_tablename = iv_table_name it_key = it_key_input ). MESSAGE 'Deleted one item.' TYPE 'I'. CATCH /aws1/cx_dyncondalcheckfaile00. MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'. CATCH /aws1/cx_dynresourcenotfoundex. MESSAGE 'The table or index does not exist' TYPE 'E'. CATCH /aws1/cx_dyntransactconflictex. MESSAGE 'Another transaction is using the item' TYPE 'E'. ENDTRY.
  • API の詳細については、AWS SDK for SAP ABAP API リファレンスの「DeleteItem」を参照してください。

Swift
SDK for Swift
注記

これはプレビューリリースの SDK に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

/// Delete a movie, given its title and release year. /// /// - Parameters: /// - title: The movie's title. /// - year: The movie's release year. /// func delete(title: String, year: Int) async throws { guard let client = self.ddbClient else { throw MoviesError.UninitializedClient } let input = DeleteItemInput( key: [ "year": .n(String(year)), "title": .s(title) ], tableName: self.tableName ) _ = try await client.deleteItem(input: input) }
  • API の詳細については、「AWS SDK for Swift API リファレンス」の「DeleteItem」を参照してください。

DynamoDB のその他の例については、「AWS SDK を使用した DynamoDB のコード例」を参照してください。