I’m trying to perform a DeleteItem operation in DynamoDB with the following conditions:
If the item with a given primary key (PK) does not exist, the delete operation should succeed.
If the item exists, it should only be deleted if a certain condition (e.g., attribute B equals a specific value) is satisfied.
The entire operation must be handled in a single request (i.e., no additional queries or transactions).
Here’s the DeleteItem request I’ve been trying (example):
deleteInput := &dynamodb.DeleteItemInput{
TableName: aws.String("YourTableName"),
Key: map[string]*dynamodb.AttributeValue{
"PK": {S: aws.String("PrimaryKeyValue")},
},
ConditionExpression: aws.String("attribute_not_exists(PK) OR #status = :statusValue"),
ExpressionAttributeNames: map[string]*string{
"#status": aws.String("Status"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":statusValue": {S: aws.String("Completed")},
},
}
_, err := dynamodbSvc.DeleteItem(deleteInput)
if err != nil {
if _, ok := err.(*dynamodb.ConditionalCheckFailedException); ok {
fmt.Println("Condition check failed: PK exists but Status is not Completed.")
} else {
fmt.Printf("Delete failed: %v\n", err)
}
} else {
fmt.Println("Delete succeeded.")
}
This works as expected when the item exists, and the condition is either satisfied or not. However, if the item does not exist, I get a ConditionalCheckFailedException instead of the operation succeeding.
From my understanding, the attribute_not_exists(PK) condition should evaluate to true when the item does not exist, allowing the operation to proceed. But this doesn’t seem to be happening.
How can I ensure that the delete operation succeeds when the item is missing, while still applying the condition check when the item exists? Is there a limitation in how DynamoDB evaluates conditions in such scenarios?
Any guidance or alternative approaches would be greatly appreciated. Thanks in advance!