从 DynamoDB 表中删除项目 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

从 DynamoDB 表中删除项目

您可以使用 Amazon Web Services Management Console、Amazon CLI 或 Amazon SDK 从 DynamoDB 表中删除项目。有关项目的更多信息,请参阅 Amazon DynamoDB 的核心组件

使用 Amazon SDK 删除 DynamoDB 表中的项目

以下代码示例显示如何使用 Amazon SDK 删除 DynamoDB 表中的项目。

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅 GitHub

/// <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 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DeleteItem

Go
SDK for Go V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

// 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 }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DeleteItem

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅 GitHub

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); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DeleteItem

JavaScript
SDK for JavaScript V3
提示

要了解如何设置和运行此示例,请参阅 GitHub

创建客户端。

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

创建文档客户端。

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

使用 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();

使用 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);

使用 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);
SDK for JavaScript V2
提示

要了解如何设置和运行此示例,请参阅 GitHub

从表中删除项目。

// 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

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") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeleteItem

Python
适用于 Python (Boto3) 的 SDK
提示

要了解如何设置和运行此示例,请参阅 GitHub

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

您可以指定条件,以便只有在项目满足特定条件时才会被删除。

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 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 DeleteItem

Ruby
SDK for Ruby
提示

要了解如何设置和运行此示例,请参阅 GitHub

# 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
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 DeleteItem

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

提示

要了解如何设置和运行此示例,请参阅 GitHub

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(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeleteItem

有关更多 DynamoDB 示例,请参阅适用于使用 Amazon SDK 的 DynamoDB 的代码示例