Supprimer un élément d'une table DynamoDB - Amazon DynamoDB

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Supprimer un élément d'une table DynamoDB

Vous pouvez supprimer des éléments des tables DynamoDB à l'aide de l'AWS Management Console, de l'AWS CLI, ou d'un kit AWS SDK. Pour plus d'informations sur les éléments, consultez Composants de base d'Amazon DynamoDB.

Supprimer un élément d'une table DynamoDB à l'aide d'un kit AWS SDK

Les exemples de code suivants montrent comment supprimer un élément d'une table DynamoDB à l'aide d'un kit AWS SDK.

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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; }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for .NET API.

Bash
AWS CLI avec le script Bash
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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 }

Fonctions utilitaires utilisées dans cet exemple.

############################################################################### # 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 }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS CLI commandes.

C++
Kit SDK pour C++
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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(); }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for C++ API.

CLI
AWS CLI

Exemple 1 : pour supprimer un élément

L'delete-itemexemple suivant supprime un élément du MusicCollection tableau et demande des informations sur l'élément supprimé et sur la capacité utilisée par la demande.

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

Contenu de key.json :

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

Sortie :

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

Pour plus d'informations, consultez la section Rédaction d'un article dans le guide du développeur Amazon DynamoDB.

Exemple 2 : pour supprimer un élément de manière conditionnelle

L'exemple suivant supprime un article du ProductCatalog tableau uniquement s'il se situe entre 500 Gardening Supplies et 600 ProductCategorySporting Goods ou si son prix est compris entre 500 et 600€. Elle renvoie des informations sur l'élément qui a été supprimé.

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

Contenu de names.json :

{ "#P": "Price" }

Contenu de values.json :

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

Sortie :

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

Pour plus d'informations, consultez la section Rédaction d'un article dans le guide du développeur Amazon DynamoDB.

  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS CLI commandes.

Go
Kit SDK for Go V2
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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"]) }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for Go API.

Java
Kit SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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); } } }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for Java 2.x API.

JavaScript
SDK pour JavaScript (v3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Cet exemple utilise le client de document pour simplifier l'utilisation d'éléments dans DynamoDB. Pour plus de détails sur l'API, voir 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 pour JavaScript (v2)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Supprimez un élément d'une table .

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

Supprimez un élément d'une table à l'aide du client de document 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
Kits SDK pour Kotlin
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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") } }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section AWSSDK pour la référence de l'API Kotlin.

PHP
Kit SDK pour PHP
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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, ]); }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for PHP API.

Python
Kit SDK pour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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

Vous pouvez spécifier une condition pour qu'un élément soit supprimé uniquement lorsqu'il répond à certains critères.

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
  • Pour plus de détails sur l'API, consultez DeleteItemle AWSmanuel de référence de l'API SDK for Python (Boto3).

Ruby
Kit SDK pour Ruby
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section Référence des AWS SDK for Ruby API.

Rust
Kit SDK pour Rust
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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)), } }
  • Pour plus de détails sur l'API, voir DeleteItemla section de référence de l'API AWS SDK for Rust.

SAP ABAP
Kit SDK pour SAP ABAP
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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.
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section de référence du AWSSDK pour l'API SAP ABAP.

Swift
Kit SDK pour Swift
Note

Ceci est une documentation préliminaire pour une fonctionnalité en version de prévisualisation. Elle est susceptible d’être modifiée.

Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code 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) }
  • Pour plus de détails sur l'API, reportez-vous DeleteItemà la section AWSSDK pour la référence de l'API Swift.

Pour obtenir plus d'exemples avec DynamoDB, consultez Exemples de code pour DynamoDB à l'aide de kits AWS SDK.