Update and Delete Entities in Azure Cosmos DB Table API
This document explains how to update and delete entities in an Azure Cosmos DB table using the Table API. Modifying and removing data are fundamental operations for managing your data store.
Updating Entities
You can update an existing entity in a table by either replacing it entirely or by merging properties into it. The Table API supports two main methods for updates:
1. Replace Entity
The ReplaceEntity operation overwrites the entire existing entity with a new one. If the entity does not exist, the operation will fail.
Example (C# SDK)
using Azure;
using Azure.Data.Tables;
// Assume 'client' is an initialized TableClient and 'entity' is an existing entity to update.
string connectionString = "YOUR_COSMOS_DB_CONNECTION_STRING";
string tableName = "MyEntities";
var client = new TableClient(connectionString, tableName);
// Retrieve the entity you want to update
var existingEntity = client.GetEntity<MyTableEntity>("PartitionKey1", "RowKey1");
if (existingEntity.HasValue)
{
MyTableEntity entityToUpdate = existingEntity.Value;
entityToUpdate.Description = "Updated description for the entity.";
entityToUpdate.Status = "Completed";
// Replace the entire entity
client.UpdateEntity(entityToUpdate, entityToUpdate.GetETag(), TableUpdateMode.Replace);
Console.WriteLine("Entity replaced successfully.");
}
else
{
Console.WriteLine("Entity not found.");
}
public class MyTableEntity : ITableEntity
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
public string Description { get; set; }
public string Status { get; set; }
}
2. Merge Entity
The MergeEntity operation updates an existing entity by merging the provided properties into it. Properties not specified in the update will remain unchanged. If the entity does not exist, the operation will fail.
Example (Python SDK)
from azure.data.tables import TableServiceClient
from azure.core.exceptions import ResourceNotFoundError
connection_string = "YOUR_COSMOS_DB_CONNECTION_STRING"
table_name = "MyEntities"
table_service_client = TableServiceClient.from_connection_string(connection_string)
table_client = table_service_client.get_table_client(table_name)
try:
# Retrieve the entity to merge properties into
entity = table_client.get_entity(partition_key="PartitionKey1", row_key="RowKey1")
# Update specific properties
entity["Description"] = "Merged description."
entity["Priority"] = 1
# Merge the entity
table_client.update_entity(entity, mode="Merge")
print("Entity merged successfully.")
except ResourceNotFoundError:
print("Entity not found.")
except Exception as e:
print(f"An error occurred: {e}")
When updating, it's good practice to use the ETag for optimistic concurrency to prevent lost updates.
Deleting Entities
Deleting an entity removes it permanently from the table. You specify the entity to delete by its PartitionKey and RowKey.
Example (Java SDK)
import com.azure.data.tables.TableClient;
import com.azure.data.tables.models.TableEntity;
import com.azure.data.tables.models.TableServiceException;
import com.azure.core.util.ETag;
// Assume 'tableClient' is an initialized TableClient.
String partitionKey = "PartitionKey1";
String rowKey = "RowKey1";
ETag etag = ETag.parse("\"0\""); // You can get the ETag from a previous get operation.
try {
tableClient.deleteEntity(partitionKey, rowKey, etag);
System.out.println("Entity deleted successfully.");
} catch (TableServiceException e) {
System.err.println("Error deleting entity: " + e.getMessage());
}
Similar to updates, you can use the ETag for optimistic concurrency when deleting an entity. If the entity's ETag does not match the provided ETag, the deletion will fail, indicating that the entity has been modified since it was last retrieved.
Considerations
- ETags: Always use ETags for optimistic concurrency control, especially in multi-user or high-throughput scenarios.
- Batch Operations: For multiple updates or deletions, consider using batch operations to improve efficiency and atomicity.
- Error Handling: Implement robust error handling for scenarios like entities not being found or concurrency conflicts.