DynamoDB 테이블에서 항목 삭제
AWS Management Console, AWS CLI 또는 AWS SDK를 사용하여 DynamoDB 테이블에서 항목을 삭제할 수 있습니다. 항목에 대한 자세한 내용은 Amazon DynamoDB의 핵심 구성 요소 섹션을 참조하세요.
AWS SDK를 사용하여 DynamoDB 테이블에서 항목 삭제
다음 코드 예제에서는 AWS SDK를 사용하여 DynamoDB 테이블에서 항목을 삭제하는 방법을 보여줍니다.
- .NET
-
- AWS SDK for .NET
-
참고 GitHub에 더 많은 내용이 있습니다. 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; }
-
API에 대한 세부 정보는 AWS SDK for .NET API 참조의 DeleteItem을 참조하세요.
-
- C++
-
- SDK for C++
-
참고 GitHub에 더 많은 내용이 있습니다. 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(); }
-
API에 대한 세부 정보는 AWS SDK for C++ API 참조의 DeleteItem을 참조하세요.
-
- Go
-
- Go V2용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. 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 }
-
API에 대한 세부 정보는 AWS SDK for Go API 참조의 DeleteItem
을 참조하세요.
-
- Java
-
- Java 2.x용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. 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에 대한 세부 정보는 AWS SDK for Java 2.x API 참조의 DeleteItem을 참조하세요.
-
- JavaScript
-
- JavaScript V3용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. 클라이언트를 생성합니다.
// 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);
-
자세한 정보는 AWS SDK for JavaScript 개발자 안내서를 참조하세요.
-
API에 대한 세부 정보는 AWS SDK for JavaScript API 참조의 DeleteItem을 참조하세요.
-
- JavaScript V2용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. 테이블에서 항목을 삭제합니다.
// 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); } });
-
자세한 정보는 AWS SDK for JavaScript 개발자 안내서를 참조하세요.
-
API에 대한 세부 정보는 AWS SDK for JavaScript API 참조의 DeleteItem을 참조하세요.
-
- Kotlin
-
- Kotlin용 SDK
-
참고 이 시험판 설명서는 미리 보기 버전 기능에 관한 것입니다. 변경될 수 있습니다.
참고 GitHub에 더 많은 내용이 있습니다. 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") } }
-
API에 대한 세부 정보는 AWS Kotlin용 SDK API 참조의 DeleteItem
을 참조하세요.
-
- PHP
-
- PHP용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. 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, ]); }
-
API에 대한 세부 정보는 AWS SDK for PHP API 참조의 DeleteItem을 참조하세요.
-
- Python
-
- Python용 SDK(Boto3)
-
참고 GitHub에 더 많은 내용이 있습니다. 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 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에 대한 세부 정보는 Python용 AWS SDK(Boto3) API 참조의 DeleteItem을 참조하세요.
-
- Ruby
-
- Ruby용 SDK
-
참고 GitHub에 더 많은 내용이 있습니다. AWS코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. # 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에 대한 세부 정보는 AWS SDK for Ruby API 참조의 DeleteItem을 참조하세요.
-
- Rust
-
- Rust용 SDK
-
참고 이 설명서는 평가판 버전 SDK에 관한 것입니다. SDK는 변경될 수 있으며 프로덕션에서 사용해서는 안 됩니다.
참고 GitHub에 더 많은 내용이 있습니다. 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)), } }
-
API에 대한 세부 정보는 Rust용 AWS SDK API 참조의 DeleteItem
을 참조하세요.
-
더 많은 DynamoDB 예제는 AWS SDK를 사용한 DynamoDB용 코드 예제 섹션을 참조하세요.