Verwendung DeleteItem mit einem AWS SDK oder CLI - Amazon-DynamoDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Verwendung DeleteItem mit einem AWS SDK oder CLI

Die folgenden Codebeispiele zeigen, wie es verwendet wirdDeleteItem.

Beispiele für Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Im folgenden Codebeispiel können Sie diese Aktion im Kontext sehen:

.NET
AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <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; }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for .NET API-Referenz.

Bash
AWS CLI mit Bash-Skript
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

############################################################################## # 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 }

Die in diesem Beispiel verwendeten Dienstprogrammfunktionen.

############################################################################### # 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 }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS CLI Befehlsreferenz.

C++
SDK für C++
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

//! 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(); }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for C++ API-Referenz.

CLI
AWS CLI

Beispiel 1: Um ein Element zu löschen

Das folgende delete-item Beispiel löscht ein Element aus der MusicCollection Tabelle und fordert Details zu dem gelöschten Element und der von der Anforderung verwendeten Kapazität an.

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

Inhalt von key.json:

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

Ausgabe:

{ "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 ] } }

Weitere Informationen finden Sie unter Artikel schreiben im Amazon DynamoDB DynamoDB-Entwicklerhandbuch.

Beispiel 2: Um einen Artikel unter bestimmten Bedingungen zu löschen

Im folgenden Beispiel wird ein Artikel nur dann aus der ProductCatalog Tabelle gelöscht, wenn er entweder Sporting Goods oder ProductCategory ist Gardening Supplies und sein Preis zwischen 500 und 600 liegt. Es gibt Details zu dem Element zurück, das gelöscht wurde.

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

Inhalt von names.json:

{ "#P": "Price" }

Inhalt von values.json:

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

Ausgabe:

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

Weitere Informationen finden Sie unter Artikel schreiben im Amazon DynamoDB DynamoDB-Entwicklerhandbuch.

Go
SDK für Go V2
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

// 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"]) }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for Go API-Referenz.

Java
SDK für Java 2.x
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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); } } }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for Java 2.x API-Referenz.

JavaScript
SDK für JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

In diesem Beispiel wird der Dokument-Client verwendet, um die Arbeit mit Elementen in DynamoDB zu vereinfachen. Einzelheiten zur API finden Sie unter 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 für JavaScript (v2)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

Löschen Sie ein Element aus einer Tabelle.

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

Löschen Sie ein Element mithilfe des DynamoDB-Dokument-Clients aus einer Tabelle.

// 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 für Kotlin
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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") } }
  • Einzelheiten zur API finden Sie DeleteItemin der API-Referenz zum AWS SDK für Kotlin.

PHP
SDK für PHP
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

$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, ]); }
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for PHP API-Referenz.

PowerShell
Tools für PowerShell

Beispiel 1: Entfernt das DynamoDB-Element, das dem angegebenen Schlüssel entspricht.

$key = @{ SongTitle = 'Somewhere Down The Road' Artist = 'No One You Know' } | ConvertTo-DDBItem Remove-DDBItem -TableName 'Music' -Key $key -Confirm:$false
Python
SDK für Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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

Sie können eine Bedingung angeben, damit ein Element nur gelöscht wird, wenn es bestimmte Kriterien erfüllt.

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
  • Einzelheiten zur API finden Sie DeleteItemin AWS SDK for Python (Boto3) API Reference.

Ruby
SDK für Ruby
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • Einzelheiten zur API finden Sie DeleteItemin der AWS SDK for Ruby API-Referenz.

Rust
SDK für Rust
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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)), } }
  • Einzelheiten zur API finden Sie DeleteItemin der API-Referenz zum AWS SDK für Rust.

SAP ABAP
SDK für SAP ABAP
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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.
  • Einzelheiten zur API finden Sie DeleteItemin der API-Referenz zum AWS SDK für SAP ABAP.

Swift
SDK für Swift
Anmerkung

Diese ist die Vorabdokumentation für ein SDK in der Vorversion. Änderungen sind vorbehalten.

Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// 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) }
  • Einzelheiten zur API finden Sie DeleteItemin der API-Referenz zum AWS SDK für Swift.

Eine vollständige Liste der AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unterDynamoDB mit einem SDK verwenden AWS. Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.