Get newest entry in Azure Table Storage

Recently I had the requirement of retreiving the newest entry in an Azure Table Storage table. While there’s of course the Timestamp column that could be used to indetify the desired row, we would need to query the whole table to find the youngest date. This could be narrowed down by for example knowing on which day a record was added and filtering accordingly, but we’d probably still get multiple rows to check manually for the newest one.

However, we can use the fact that all rows in the Azure Table Storage are sorted by PartitionKey + RowKey to our advantage. By making sure this combination comes first in alphabetical order for every new entry makes it easy to just ask for the very first row.

One way to ensure this is by converting the current DateTime to a ever-decreasing number of ticks by subtracting it from the DateTime.Max value. Before using it as a PrimaryKey or RowKey we do need to convert this to a string while making sure all future values have the same length with leading zeroes when necessary.

These two helper methods show how to do this and how to convert the ticks string back to DateTimeOffset. You can copy the code or use my NuGet library.

/// <summary>
/// Returns an ever-decreasing number as string to be used as PartitionKey or RowKey.
/// Ensures that newly created entities are always "on top" and returned first in queries
/// </summary>
/// <returns></returns>
public static string TicksKey()
{
return (DateTime.MaxValue.Ticks – DateTime.UtcNow.Ticks).ToString("d19");
}
/// <summary>
/// Converts TicksKey back to DateTimeOffset
/// </summary>
/// <param name="ticksKey"></param>
/// <returns></returns>
public static DateTimeOffset TicksKeyToDateTimeOffset(string ticksKey)
{
return new DateTimeOffset(DateTime.MaxValue.Ticks – long.Parse(ticksKey), TimeSpan.Zero);
}

After we have our Table Storage structure in place we can efficiently query the very first row by limiting the items per page of our query to just one element. Again, this is written as an extension method to the Azure.Data.Tables SDK to make it clean & easy to reuse the code.

/// <summary>
/// Returns first entity in the table
/// </summary>
/// <typeparam name="T">Implementation of ITableEntity</typeparam>
/// <param name="tableClient">The authenticated TableClient</param>
/// <returns>First entity in table</returns>
public static async Task<T> GetFirstEntityAsync<T>(this TableClient tableClient) where T : class, ITableEntity, new()
{
return await tableClient.QueryAsync<T>(maxPerPage: 1).FirstOrDefaultAsync();
}

Note: This code makes use of the System.Linq.Async NuGet package which makes working with the Azure Table Storage SDK a lot cleaner.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.