[Yandex Cloud documentation](../../../../index.md) > [Yandex Managed Service for YDB](../../../index.md) > Amazon DynamoDB-compatible Document API > Tools > [Working with the AWS SDK](index.md) > Managing records in a table > Deleting a record

# Deleting a record

To conditionally delete a record from the `Series` table:

{% list tabs group=programming_language %}

- Java {#java}

  1. Create the `SeriesItemOps06` project:

      ```bash
      mvn -B archetype:generate \
        -DarchetypeGroupId=org.apache.maven.archetypes \
        -DgroupId=com.mycompany.app \
        -DartifactId=SeriesItemOps06
      ```

      This command will create the `SeriesItemOps06` project folder in the current working folder, with a subfolder structure and the `pom.xml` project description file.
  
  1. Go to the project folder:

      ```bash
      cd SeriesItemOps06
      ```

  1. Edit the project description in the `pom.xml` file, e.g., using `nano`:

      ```bash
      nano pom.xml
      ```

      Example of the `pom.xml` file:

      ```xml
      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mycompany.app</groupId>
        <artifactId>SeriesItemOps06</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SeriesItemOps06</name>
        <url>http://maven.apache.org</url>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <configuration>
                        <archive>
                            <manifest>
                                <addClasspath>true</addClasspath>
                                <classpathPrefix>lib/</classpathPrefix>
                                <mainClass>com.mycompany.app.SeriesItemOps06</mainClass>
                            </manifest>
                            <manifestEntries>
                                <Class-Path>.</Class-Path>
                            </manifestEntries>
                        </archive>
                        <finalName>release/SeriesItemOps06</finalName>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>copy-dependencies</id>
                            <phase>prepare-package</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/release/lib</outputDirectory>
                                <overWriteReleases>false</overWriteReleases>
                                <overWriteSnapshots>false</overWriteSnapshots>
                                <overWriteIfNewer>true</overWriteIfNewer>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
        <dependencies>
          <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
          </dependency>
          <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.11.1012</version>
          </dependency>
        </dependencies>
        <properties>
          <maven.compiler.source>1.8</maven.compiler.source>
          <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
      </project>
      ```

      Check the current versions of [junit](https://mvnrepository.com/artifact/junit/junit) and [aws-java-sdk-dynamodb](https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-dynamodb).

  1. In the `src/main/java/com/mycompany/app/` folder, create the `SeriesItemOps06.java` file, e.g., using `nano`:
  
      ```bash
      nano src/main/java/com/mycompany/app/SeriesItemOps06.java
      ```

      Paste the following code into this file:

      {% note warning %}

      Specify the value you [prepared earlier](index.md#before-you-begin) instead of `<Document_API_endpoint>`.

      {% endnote %}

      ```java
      package com.mycompany.app;

      import com.amazonaws.client.builder.AwsClientBuilder;
      import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
      import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
      import com.amazonaws.services.dynamodbv2.document.DynamoDB;
      import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
      import com.amazonaws.services.dynamodbv2.document.Table;
      import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
      import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;

      public class SeriesItemOps06 {

          public static void main(String[] args) throws Exception {

              AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
                  .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("<Document_API_endpoint>", "ru-central1"))
                  .build();

              DynamoDB dynamoDB = new DynamoDB(client);

              Table table = dynamoDB.getTable("Series");

              int series_id = 3;
              String title = "Supernatural";

              DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
                  .withPrimaryKey(new PrimaryKey("series_id", series_id, "title", title)).withConditionExpression("info.rating <= :val")
                  .withValueMap(new ValueMap().withNumber(":val", 5));

              try {
                  System.out.println("Trying to delete record...");
                  table.deleteItem(deleteItemSpec);
                  System.out.println("Series data deleted.");
              }
              catch (Exception e) {
                  System.err.println("Couldn't delete record: " + series_id + " " + title);
                  System.err.println(e.getMessage());
              }
    
          }
      }
      ```

      This code will delete a movie record if its rating is 5 or lower.

      You can use the `deleteItem` method to delete a single record by specifying its primary key. You can additionally specify `ConditionExpression` to prevent the item from being deleted if this condition is not met.

  1. Build the project:

      ```bash
      mvn package
      ```

      This command will create the `SeriesItemOps06.jar` file in the `target/release/` folder.

  1. Run the application:

      ```bash
      java -jar target/release/SeriesItemOps06.jar
      ```

      Result:

      ```text
      Attempting to delete record...
      Couldn't delete record: 3 Supernatural
      Condition not satisfied (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ConditionalCheckFailedException; Request ID: null; Proxy: null)
      ```

      Error completing operation: movie rating is higher than 5.

      Change the code by deleting the condition in `DeleteItemSpec`:

      ```java
      DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
          .withPrimaryKey(new PrimaryKey("series_id", series_id, "title", title));
      ```

      Re-build the project and run the application:

      ```bash
      mvn package && java -jar target/release/SeriesItemOps06.jar
      ```

      Now the operation is successful:

      ```text
      Attempting to delete record...
      Series data deleted.
      ```

- Python {#python}

  1. Create the `SeriesItemOps06.py` file, e.g., using `nano`:
  
      ```bash
      nano SeriesItemOps06.py
      ```

      Paste the following code into this file:

      {% note warning %}

      Specify the value you [prepared earlier](index.md#before-you-begin) instead of `<Document_API_endpoint>`.

      {% endnote %}

      ```python
      from decimal import Decimal
      from pprint import pprint
      import boto3
      from botocore.exceptions import ClientError

      def delete_underrated_serie(title, series_id, rating):
          ydb_docapi_client = boto3.resource('dynamodb', endpoint_url = "<Document_API_endpoint>")

          table = ydb_docapi_client.Table('Series')

          try:
              response = table.delete_item(
                  Key = {
                      'series_id': series_id,
                      'title': title
                  },
                  ConditionExpression = "info.rating <= :val",
                  ExpressionAttributeValues = {
                      ":val": Decimal(rating)
                  }
              )
          except ClientError as e:
              if e.response['Error']['Code'] == "ConditionalCheckFailedException":
                  print(e.response['Error']['Message'])
              else:
                  raise
          else:
              return response

      if __name__ == '__main__':
          print("Trying to delete record...")
          delete_response = delete_underrated_serie("Supernatural", 3, 5)
          if delete_response:
              print("Series data deleted:")
              pprint(delete_response, sort_dicts = False)
      ```

      The above code will delete a record if the series rating is 5 or lower.

      To delete a record, use the `delete_item` method and provide the primary key of the record in question. You can set a condition for deleting a record by specifying the `ConditionExpression` parameter.

  1. Run the program:

      ```bash
      python SeriesItemOps06.py
      ```

      Result:

      ```text
      Attempting to delete record...
      Condition not satisfied
      ```

      Error completing operation: movie rating is higher than 5.

  1. Change the code by deleting the condition:

      ```python
      response = table.delete_item(
          Key = {
              'series_id': series_id,
              'title': title
          }
      )
      ```

  1. Run the program again. The delete operation should now be successful.

      Result:

      ```text
      Attempting to delete record...
      Series data deleted:
      {'ResponseMetadata': {'HTTPStatusCode': 200,
                            'HTTPHeaders': {'content-type': 'application/x-amz-json-1.0',
                                            'x-amz-crc32': '2745614147',
                                            'x-request-id': '786fed1d-3c71-4fee-9827-f3f28da0493e',
                                            'date': 'Wed, 13 Jan 2021 11:04:13 GMT',
                                            'content-length': '2'},
                            'RetryAttempts': 0}}
      ```

- PHP {#php}

  1. Create the `SeriesItemOps06.php` file, e.g., using `nano`:
  
      ```bash
      nano SeriesItemOps06.php
      ```

      Paste the following code into this file:

      {% note warning %}

      Specify the value you [prepared earlier](index.md#before-you-begin) instead of `<Document_API_endpoint>`.

      {% endnote %}

      ```php
      <?php

      require 'vendor/autoload.php';

      date_default_timezone_set('UTC');

      use Aws\DynamoDb\Exception\DynamoDbException;
      use Aws\DynamoDb\Marshaler;

      $sdk = new Aws\Sdk([
          'endpoint' => '<Document_API_endpoint>',
          'region'   => 'ru-central1',
          'version'  => 'latest'
      ]);

      $dynamodb = $sdk->createDynamoDb();
      $marshaler = new Marshaler();

      $tableName = 'Series';

      $series_id = 3;
      $title = 'Supernatural';

      $key = $marshaler->marshalJson('
          {
              "series_id": ' . $series_id . ',
              "title": "' . $title . '"
          }
      ');

      $eav = $marshaler->marshalJson('
          {
              ":val": 5
          }
      ');

      $params = [
          'TableName' => $tableName,
          'Key' => $key,
          'ConditionExpression' => 'info.rating <= :val',
          'ExpressionAttributeValues'=> $eav
      ];

      try {
          $result = $dynamodb->deleteItem($params);
          echo "Record deleted.\n";

      } catch (DynamoDbException $e) {
          echo "Couldn't delete record:\n";
          echo $e->getMessage() . "\n";
      }

      ?>
      ```

      You can use the `deleteItem` method to delete a single record by specifying its primary key. You can additionally specify `ConditionExpression` to prevent the item from being deleted if this condition is not met.

      This code will delete a movie record if its rating is 5 or lower.

  1. Run the program:

      ```bash
      php SeriesItemOps06.php
      ```

      Result:

      ```text
      Couldn't delete item:
      ...
      ConditionalCheckFailedException (client): Condition not satisfied
      ...
      ```

      Error completing operation: movie rating is higher than 5.

      Change the code by deleting the condition:

      ```php
      $params = [
          'TableName' => $tableName,
          'Key' => $key
      ];
      ```

      Run the program again. Now the operation is successful:

      ```text
      Record deleted.
      ```

- Node.js {#node}

  1. Create the `SeriesItemOps06.js` file, e.g., using `nano`:

      ```bash
      nano SeriesItemOps06.js
      ```

      Paste the following code into this file:

      {% note warning %}

      Specify the value you [prepared earlier](index.md#before-you-begin) instead of `<Document_API_endpoint>`.

      {% endnote %}

      ```javascript
      const AWS = require("@aws-sdk/client-dynamodb");
      const { marshall } = require("@aws-sdk/util-dynamodb");

      // Credentials should be defined via environment variables AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID
      const dynamodb = new AWS.DynamoDBClient({
          region: "ru-central1",
          endpoint: "<Document_API_endpoint>",
      });

      const table = "Series";
      const series_id = 3;
      const title = "Supernatural";

      const params = {
          TableName: table,
          Key: marshall({
              "series_id": series_id,
              "title": title
          }),
          ConditionExpression: "info.rating >= :val",
          ExpressionAttributeValues: marshall({
              ":val": 10
          })
      };

      console.log("Performing conditional deletion...");

      dynamodb.send(new AWS.DeleteItemCommand(params))
          .then(data => {
              console.log("Successfully deleted:", JSON.stringify(data, null, 2));
          })
          .catch(err => {
              console.error("Couldn't delete item. JSON error:", JSON.stringify(err, null, 2));
              process.exit(1);
          })
      ```

      You can delete a single record with the `DeleteItemCommand` command by specifying its primary key. You can additionally specify `ConditionExpression` to prevent the item from being deleted if this condition is not met.

  1. Run the program:

      ```bash
      node SeriesItemOps06.js
      ```

      Result:

      ```text
      Performing conditional deletion...
      Couldn't delete record. JSON error: {
        "message": "Condition not satisfied",
        "code": "ConditionalCheckFailedException",
        "time": "2021-06-14T20:33:29.115Z",
        "statusCode": 400,
        "retryable": false,
        "retryDelay": 20.94065998018778
      }
      ```

      Error completing operation: movie rating is lower than 10.

      Change the code by deleting the condition:

      ```javascript
      const params = {
          TableName: table,
          Key: marshall({
              "series_id": series_id,
              "title": title
          }),
      };
      ```

      Run the program again. Now the operation is successful:

      ```text
      Performing conditional deletion...
      Deletion successful: {}
      ```

- Ruby {#ruby}

  1. Create the `SeriesItemOps06.rb` file, e.g., using `nano`:

      ```bash
      nano SeriesItemOps06.rb
      ```

      Paste the following code into this file:

      {% note warning %}

      Specify the value you [prepared earlier](index.md#before-you-begin) instead of `<Document_API_endpoint>`.

      {% endnote %}

      ```ruby
      require 'aws-sdk-dynamodb'

      def table_item_deleted?(dynamodb_client, table_item)
        dynamodb_client.delete_item(table_item)
        true
      rescue StandardError => e
        puts "Error deleting item: #{e.message}"
        false
      end

      def run_me
        region = 'ru-central1'
        table_name = 'Series'
        title = 'Supernatural'
        series_id = 3

        Aws.config.update(
          endpoint: '<Document_API_endpoint>',
          region: region
        )

        dynamodb_client = Aws::DynamoDB::Client.new

        table_item = {
          table_name: table_name,
          key: {
            series_id: series_id,
            title: title
          },
          condition_expression: 'info.rating > :val',
            expression_attribute_values: {
              ':val' => 9
            }
        }

        puts "Deleting series '#{title} (#{series_id})' from the table '#{table_name}' if the specified condition is satisfied."

        if table_item_deleted?(dynamodb_client, table_item)
          puts 'Record deleted.'
        else
          puts 'Couldn't delete record.'
        end
      end

      run_me if $PROGRAM_NAME == __FILE__
      ```

      You can use the delete `delete` method to delete a single record by specifying its primary key. You can additionally specify `ConditionExpression` to prevent the item from being deleted if this condition is not met.

  1. Run the program:

      ```bash
      ruby SeriesItemOps06.rb
      ```

      Result:

      ```text
      Deleting series 'Supernatural (3)' from 'Series' table if the specified condition is satisfied.
      Error deleting record: condition not satisfied
      Couldn't delete record.
      ```

      Error completing operation: movie rating is 9.

      Change the code by deleting the condition:

      ```ruby
      table_item = {
        table_name: table_name,
        key: {
          series_id: series_id,
          title: title
        }
      }
      ```

      Run the program again. Now the operation is successful:

      ```text
      Deleting series 'Supernatural (3)' from 'Series' table if the specified condition is satisfied.
      Record deleted.
      ```

{% endlist %}