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 Principaux composants 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
-
/// <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; }
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, consultez DeleteItem dans la référence d'API AWS SDK for .NET.
-
- Go
-
- Kit SDK for Go V2
-
// 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 }
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, consultez DeleteItem
dans la référence d'API AWS SDK for Go.
-
- Java
-
- SDK pour Java 2.x
-
public static void deleteDymamoDBItem(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); } }
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, consultez DeleteItem dans la référence d'API AWS SDK for Java 2.x.
-
- JavaScript
-
- SDK pour JavaScript V3
-
Créez le client.
// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });
Créez le client de document.
// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };
Supprimez un élément d'une table à l'aide du client de document DynamoDB.
import { DeleteCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { TableName: "TABLE_NAME", Key: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; export const deleteItem = async () => { try { const data = await ddbDocClient.send(new DeleteCommand(params)); console.log("Success - item deleted"); } catch (err) { console.log("Error", err); } }; deleteItem();
Supprimez un élément d'une table à l'aide de PartiQL.
// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieYear1, movieTitle1) => { const params = { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1);
Supprimez un élément d'une table par lot à l'aide de PartiQL.
// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { try { const params = { Statements: [ { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear1 }, { S: movieTitle1 }], }, { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear2 }, { S: movieTitle2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items deleted.", data); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour de plus amples informations, consultez le AWS SDK for JavaScript Guide du développeur.
-
Pour plus d'informations sur l'API, consultez DeleteItem dans la référence d'API AWS SDK for JavaScript.
-
- Kit SDK pour JavaScript V2
-
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); } });
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour de plus amples informations, consultez le AWS SDK for JavaScript Guide du développeur.
-
Pour plus d'informations sur l'API, consultez DeleteItem dans la référence d'API AWS SDK for JavaScript.
-
- Kotlin
-
- Kits SDK pour Kotlin
-
Note Ceci est une documentation préliminaire pour une fonctionnalité en version de prévisualisation. Elle est susceptible d'être modifiée.
suspend fun deleteDymamoDBItem(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") } }
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour obtenir plus de détails sur l'API, consultez DeleteItem
dans la référence d'API du kit AWS SDK pour Kotlin.
-
- Python
-
- SDK pour Python (Boto3)
-
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 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
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, veuillez consulter DeleteItem dans la référence d'API du kit AWS SDK pour Python (Boto3).
-
- Ruby
-
- Kit SDK for Ruby
-
# 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_movie(title, year) @table.delete_item(key: {"year" => year, "title" => title}) rescue Aws::Errors::ServiceError => e puts("Couldn't delete movie #{title}. Here's why:") puts("\t#{e.code}: #{e.message}") raise end
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, consultez DeleteItem dans la référence d'API AWS SDK for Ruby.
-
- Rust
-
- Kit SDK pour Rust
-
Note Cette documentation concerne un kit SDK en prévisualisation préliminaire. Le kit SDK est susceptible d'être modifié et ne doit pas être utilisé en production.
async fn delete_item(client: &Client, table: &str, key: &str, value: &str) -> Result<(), Error> { match client .delete_item() .table_name(table) .key(key, AttributeValue::S(value.into())) .send() .await { Ok(_) => println!("Deleted item from table"), Err(e) => { println!("Got an error deleting item from table:"); println!("{}", e); process::exit(1); } }; Ok(()) }
-
Trouvez des instructions et plus de code sur GitHub
. -
Pour plus d'informations sur l'API, consultez DeleteItemt
dans la référence d'API du kit AWS SDK pour Rust.
-
Pour obtenir plus d'exemples avec DynamoDB, consultez Exemples de code pour Amazon S3 utilisant des kits AWS SDK.