Skip to content

delete_item

delete_item(
    table_name: TableArn,
    key: Key,
    *,
    config_overrides: Optional[DynamoDBClientConfig] = None,
    expected: Optional[ExpectedAttributeMap] = None,
    conditional_operator: Optional[ConditionalOperator] = None,
    return_values: Optional[ReturnValue] = None,
    return_consumed_capacity: Optional[ReturnConsumedCapacity] = None,
    return_item_collection_metrics: Optional[ReturnItemCollectionMetrics] = None,
    condition_expression: Optional[ConditionExpression] = None,
    expression_attribute_names: Optional[ExpressionAttributeNameMap] = None,
    expression_attribute_values: Optional[ExpressionAttributeValueMap] = None,
    return_values_on_condition_check_failure: Optional[
        ReturnValuesOnConditionCheckFailure
    ] = None,
) -> DeleteItemOutput

Deletes a single item in a table by primary key. You can perform a conditional delete operation that deletes the item if it exists, or if it has an expected attribute value.

In addition to deleting an item, you can also return the item's attribute values in the same operation, using the ReturnValues parameter.

Unless you specify conditions, the DeleteItem is an idempotent operation; running it multiple times on the same item or attribute does not result in an error response.

Conditional deletes are useful for deleting items only if specific conditions are met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item is not deleted.

Parameters:

  • table_name (TableArn) –

    The name of the table from which to delete the item. You can also provide the Amazon Resource Name (ARN) of the table in this parameter.

  • key (Key) –

    A map of attribute names to AttributeValue objects, representing the primary key of the item to delete.

    For the primary key, you must provide all of the key attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.

  • expected (Optional[ExpectedAttributeMap], default: None ) –

    This is a legacy parameter. Use ConditionExpression instead. For more information, see Expected in the Amazon DynamoDB Developer Guide.

  • conditional_operator (Optional[ConditionalOperator], default: None ) –

    This is a legacy parameter. Use ConditionExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide.

  • return_values (Optional[ReturnValue], default: None ) –

    Use ReturnValues if you want to get the item attributes as they appeared before they were deleted. For DeleteItem, the valid values are:

    • NONE - If ReturnValues is not specified, or if its value is NONE, then nothing is returned. (This setting is the default for ReturnValues.)

    • ALL_OLD - The content of the old item is returned.

    There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.

    The ReturnValues parameter is used by several DynamoDB operations; however, DeleteItem does not recognize any values other than NONE or ALL_OLD.

  • return_item_collection_metrics (Optional[ReturnItemCollectionMetrics], default: None ) –

    Determines whether item collection metrics are returned. If set to SIZE, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.

  • condition_expression (Optional[ConditionExpression], default: None ) –

    A condition that must be satisfied in order for a conditional DeleteItem to succeed.

    An expression can contain any of the following:

    • Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size

      These function names are case-sensitive.

    • Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN

    • Logical operators: AND | OR | NOT

    For more information about condition expressions, see Condition Expressions in the Amazon DynamoDB Developer Guide.

  • expression_attribute_names (Optional[ExpressionAttributeNameMap], default: None ) –

    One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames:

    • To access an attribute whose name conflicts with a DynamoDB reserved word.

    • To create a placeholder for repeating occurrences of an attribute name in an expression.

    • To prevent special characters in an attribute name from being misinterpreted in an expression.

    Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:

    • Percentile

    The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide). To work around this, you could specify the following for ExpressionAttributeNames:

    • {"#P":"Percentile"}

    You could then use this substitution in an expression, as in this example:

    • #P = :val

    Tokens that begin with the : character are expression attribute values, which are placeholders for the actual value at runtime.

    For more information on expression attribute names, see Specifying Item Attributes in the Amazon DynamoDB Developer Guide.

  • expression_attribute_values (Optional[ExpressionAttributeValueMap], default: None ) –

    One or more values that can be substituted in an expression.

    Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:

    Available | Backordered | Discontinued

    You would first need to specify ExpressionAttributeValues as follows:

    { ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }

    You could then use these values in an expression, such as this:

    ProductStatus IN (:avail, :back, :disc)

    For more information on expression attribute values, see Condition Expressions in the Amazon DynamoDB Developer Guide.

  • return_values_on_condition_check_failure (Optional[ReturnValuesOnConditionCheckFailure], default: None ) –

    An optional parameter that returns the item attributes for a DeleteItem operation that failed a condition check.

    There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.

Raises:

  • ConditionalCheckFailedException –

    A condition specified in the operation failed to be evaluated.

  • InternalServerError –

    An error occurred on the server side.

  • ItemCollectionSizeLimitExceededException –

    An item collection is too large. This exception is only returned for tables that have one or more local secondary indexes.

  • ProvisionedThroughputExceededException –

    The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception. The Amazon Web Services SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to Error Retries and Exponential Backoff in the Amazon DynamoDB Developer Guide.

  • ReplicatedWriteConflictException –

    The request was rejected because one or more items in the request are being modified by a request in another Region.

  • RequestLimitExceeded –

    Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception. Contact Amazon Web Services Support to request a quota increase.

  • ResourceNotFoundException –

    The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be ACTIVE.

  • ThrottlingException –

    The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception.

  • TransactionConflictException –

    Operation was rejected because there is an ongoing transaction for the item.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

To delete an item This example deletes an item from the Music table.

>>> client.delete_item(table_name='Music', key={'Artist': {'S': 'No One You Know'}, 'SongTitle': {'S': 'Scared of My Shadow'}})
Source code in docs_src/capo_dynamodb/_services/dynamo_db.py
def delete_item(
    self,
    table_name: "capo_dynamodb.types.table_arn.TableArn",
    key: "capo_dynamodb.types.key.Key",
    *,
    config_overrides: Optional[DynamoDBClientConfig] = None,
    expected: Optional[
        "capo_dynamodb.types.expected_attribute_map.ExpectedAttributeMap"
    ] = None,
    conditional_operator: Optional[
        "capo_dynamodb.types.conditional_operator.ConditionalOperator"
    ] = None,
    return_values: Optional["capo_dynamodb.types.return_value.ReturnValue"] = None,
    return_consumed_capacity: Optional[
        "capo_dynamodb.types.return_consumed_capacity.ReturnConsumedCapacity"
    ] = None,
    return_item_collection_metrics: Optional[
        "capo_dynamodb.types.return_item_collection_metrics.ReturnItemCollectionMetrics"
    ] = None,
    condition_expression: Optional[
        "capo_dynamodb.types.condition_expression.ConditionExpression"
    ] = None,
    expression_attribute_names: Optional[
        "capo_dynamodb.types.expression_attribute_name_map.ExpressionAttributeNameMap"
    ] = None,
    expression_attribute_values: Optional[
        "capo_dynamodb.types.expression_attribute_value_map.ExpressionAttributeValueMap"
    ] = None,
    return_values_on_condition_check_failure: Optional[
        "capo_dynamodb.types.return_values_on_condition_check_failure.ReturnValuesOnConditionCheckFailure"
    ] = None,
) -> "capo_dynamodb.types.delete_item_output.DeleteItemOutput":
    """<p>Deletes a single item in a table by primary key. You can perform a conditional delete operation that deletes the item if it exists, or if it has an expected attribute value.</p> <p>In addition to deleting an item, you can also return the item's attribute values in the same operation, using the <code>ReturnValues</code> parameter.</p> <p>Unless you specify conditions, the <code>DeleteItem</code> is an idempotent operation; running it multiple times on the same item or attribute does <i>not</i> result in an error response.</p> <p>Conditional deletes are useful for deleting items only if specific conditions are met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item is not deleted.</p>

    Args:
        table_name: <p>The name of the table from which to delete the item. You can also provide the Amazon Resource Name (ARN) of the table in this parameter.</p>
        key: <p>A map of attribute names to <code>AttributeValue</code> objects, representing the primary key of the item to delete.</p> <p>For the primary key, you must provide all of the key attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</p>
        expected: <p>This is a legacy parameter. Use <code>ConditionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.Expected.html">Expected</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        conditional_operator: <p>This is a legacy parameter. Use <code>ConditionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html">ConditionalOperator</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        return_values: <p>Use <code>ReturnValues</code> if you want to get the item attributes as they appeared before they were deleted. For <code>DeleteItem</code>, the valid values are:</p> <ul> <li> <p> <code>NONE</code> - If <code>ReturnValues</code> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <code>ReturnValues</code>.)</p> </li> <li> <p> <code>ALL_OLD</code> - The content of the old item is returned.</p> </li> </ul> <p>There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.</p> <note> <p>The <code>ReturnValues</code> parameter is used by several DynamoDB operations; however, <code>DeleteItem</code> does not recognize any values other than <code>NONE</code> or <code>ALL_OLD</code>.</p> </note>
        return_item_collection_metrics: <p>Determines whether item collection metrics are returned. If set to <code>SIZE</code>, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to <code>NONE</code> (the default), no statistics are returned.</p>
        condition_expression: <p>A condition that must be satisfied in order for a conditional <code>DeleteItem</code> to succeed.</p> <p>An expression can contain any of the following:</p> <ul> <li> <p>Functions: <code>attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size</code> </p> <p>These function names are case-sensitive.</p> </li> <li> <p>Comparison operators: <code>= | <> | < | > | <= | >= | BETWEEN | IN </code> </p> </li> <li> <p> Logical operators: <code>AND | OR | NOT</code> </p> </li> </ul> <p>For more information about condition expressions, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Condition Expressions</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        expression_attribute_names: <p>One or more substitution tokens for attribute names in an expression. The following are some use cases for using <code>ExpressionAttributeNames</code>:</p> <ul> <li> <p>To access an attribute whose name conflicts with a DynamoDB reserved word.</p> </li> <li> <p>To create a placeholder for repeating occurrences of an attribute name in an expression.</p> </li> <li> <p>To prevent special characters in an attribute name from being misinterpreted in an expression.</p> </li> </ul> <p>Use the <b>#</b> character in an expression to dereference an attribute name. For example, consider the following attribute name:</p> <ul> <li> <p> <code>Percentile</code> </p> </li> </ul> <p>The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you could specify the following for <code>ExpressionAttributeNames</code>:</p> <ul> <li> <p> <code>{"#P":"Percentile"}</code> </p> </li> </ul> <p>You could then use this substitution in an expression, as in this example:</p> <ul> <li> <p> <code>#P = :val</code> </p> </li> </ul> <note> <p>Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, which are placeholders for the actual value at runtime.</p> </note> <p>For more information on expression attribute names, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Specifying Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        expression_attribute_values: <p>One or more values that can be substituted in an expression.</p> <p>Use the <b>:</b> (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the <i>ProductStatus</i> attribute was one of the following: </p> <p> <code>Available | Backordered | Discontinued</code> </p> <p>You would first need to specify <code>ExpressionAttributeValues</code> as follows:</p> <p> <code>{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }</code> </p> <p>You could then use these values in an expression, such as this:</p> <p> <code>ProductStatus IN (:avail, :back, :disc)</code> </p> <p>For more information on expression attribute values, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Condition Expressions</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        return_values_on_condition_check_failure: <p>An optional parameter that returns the item attributes for a <code>DeleteItem</code> operation that failed a condition check.</p> <p>There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.</p>

    Raises:
        capo_dynamodb.errors.conditional_check_failed_exception.ConditionalCheckFailedException: <p>A condition specified in the operation failed to be evaluated.</p>
        capo_dynamodb.errors.internal_server_error.InternalServerError: <p>An error occurred on the server side.</p>
        capo_dynamodb.errors.invalid_endpoint_exception.InvalidEndpointException
        capo_dynamodb.errors.item_collection_size_limit_exceeded_exception.ItemCollectionSizeLimitExceededException: <p>An item collection is too large. This exception is only returned for tables that have one or more local secondary indexes.</p>
        capo_dynamodb.errors.provisioned_throughput_exceeded_exception.ProvisionedThroughputExceededException: <p>The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception. The Amazon Web Services SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        capo_dynamodb.errors.replicated_write_conflict_exception.ReplicatedWriteConflictException: <p>The request was rejected because one or more items in the request are being modified by a request in another Region. </p>
        capo_dynamodb.errors.request_limit_exceeded.RequestLimitExceeded: <p>Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception. Contact <a href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a quota increase.</p>
        capo_dynamodb.errors.resource_not_found_exception.ResourceNotFoundException: <p>The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be <code>ACTIVE</code>.</p>
        capo_dynamodb.errors.throttling_exception.ThrottlingException: <p>The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception.</p>
        capo_dynamodb.errors.transaction_conflict_exception.TransactionConflictException: <p>Operation was rejected because there is an ongoing transaction for the item.</p>
        capo_dynamodb.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        To delete an item
        This example deletes an item from the Music table.

        >>> client.delete_item(table_name='Music', key={'Artist': {'S': 'No One You Know'}, 'SongTitle': {'S': 'Scared of My Shadow'}})
    """

    def _handler(
        req: "OperationRequest[capo_dynamodb.types.delete_item_input.DeleteItemInput]",
    ) -> OperationResponse[
        "capo_dynamodb.types.delete_item_output.DeleteItemOutput"
    ]:
        import capo_dynamodb._operations.dynamo_db_20120810.delete_item

        output, http_response = (
            capo_dynamodb._operations.dynamo_db_20120810.delete_item.delete_item(
                req.options, req.input
            )
        )
        return OperationResponse(output=output, response=http_response)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("DeleteItem")
    )
    input_: capo_dynamodb.types.delete_item_input.DeleteItemInput = {
        "table_name": table_name,
        "key": key,
    }
    if expected is not None:
        input_["expected"] = expected
    if conditional_operator is not None:
        input_["conditional_operator"] = conditional_operator
    if return_values is not None:
        input_["return_values"] = return_values
    if return_consumed_capacity is not None:
        input_["return_consumed_capacity"] = return_consumed_capacity
    if return_item_collection_metrics is not None:
        input_["return_item_collection_metrics"] = return_item_collection_metrics
    if condition_expression is not None:
        input_["condition_expression"] = condition_expression
    if expression_attribute_names is not None:
        input_["expression_attribute_names"] = expression_attribute_names
    if expression_attribute_values is not None:
        input_["expression_attribute_values"] = expression_attribute_values
    if return_values_on_condition_check_failure is not None:
        input_["return_values_on_condition_check_failure"] = (
            return_values_on_condition_check_failure
        )

    response = execute_pipeline(
        OperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    response.response.close()
    return response.output