使用 Amazon SDK 删除 DynamoDB 表中的项目
以下代码示例显示如何删除 DynamoDB 表中的项目。
- .NET
-
- Amazon SDK for .NET
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 /// <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。
-
- C++
-
- 适用于 C++ 的 SDK
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 //! 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 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DeleteItem。
-
- Go
-
- SDK for Go V2
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 // 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DeleteItem。
-
- JavaScript
-
- SDK for JavaScript V3
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 创建客户端。
// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DEFAULT_REGION } from "../../../../libs/utils/util-aws-sdk.js"; // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: DEFAULT_REGION });
创建文档客户端。
// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; 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: true, // 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. }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, { marshallOptions, unmarshallOptions, }); 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 { 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 { 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);
-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 DeleteItem。
-
- SDK for JavaScript V2
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 从表中删除项目。
// 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); } });
-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 DeleteItem。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeleteItem
。
-
- PHP
-
- SDK for PHP
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 $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 详细信息,请参阅《Amazon SDK for PHP API 参考》中的 DeleteItem。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意 在 GitHub 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 # 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 上查看更多内容。在 Amazon 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 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 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeleteItem
。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 结合使用 DynamoDB 与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。