We have a requirement to purge the Azure WADLogs table on a periodic basis. We are achieving this by using Entity group transactions to delete the records older than 15 days. The logic is like this.
bool recordDoesNotExistExceptionOccured = false;
CloudTable wadLogsTable = tableClient.GetTableReference(WADLogsTableName);
partitionKey = "0" + DateTime.UtcNow.AddDays(noOfDays).Ticks;
TableQuery<WadLogsEntity> buildQuery = new TableQuery<WadLogsEntity>().Where(
TableQuery.GenerateFilterCondition("PartitionKey",
QueryComparisons.LessThanOrEqual, partitionKey));
while (!recordDoesNotExistExceptionOccured)
{
IEnumerable<WadLogsEntity> result = wadLogsTable.ExecuteQuery(buildQuery).Take(1000);
//// Batch entity delete.
if (result != null && result.Count() > 0)
{
Dictionary<string, TableBatchOperation> batches = new Dictionary<string, TableBatchOperation>();
foreach (var entity in result)
{
TableOperation tableOperation = TableOperation.Delete(entity);
if (!batches.ContainsKey(entity.PartitionKey))
{
batches.Add(entity.PartitionKey, new TableBatchOperation());
}
// A Batch Operation allows a maximum 100 entities in the batch which must share the same PartitionKey.
if (batches[entity.PartitionKey].Count < 100)
{
batches[entity.PartitionKey].Add(tableOperation);
}
}
// Execute batches.
foreach (var batch in batches.Values)
{
try
{
await wadLogsTable.ExecuteBatchAsync(batch);
}
catch (Exception exception)
{
// Log exception here.
// Set flag.
if (exception.Message.Contains(ResourceDoesNotExist))
{
recordDoesNotExistExceptionOccured = true;
}
break;
}
}
}
else
{
break;
}
}
My questions are:
- Is this an efficient way to purge the WADLogs table? If not, what can make this better?
- Is this the correct way to handle the "Specified resource does not exist exception"? If not, how can I make this better?
- Would this logic fail in any particular case?
- How would this approach change if this code is in a worker which has multiple instances deployed?
I have come up with this code by referencing the solution given here.