Storing Windows Azure Storage Table Entities in Descending Order

March 1, 2013 — 1 Comment

Windows Azure Table Storage stores Entities in ascending order based on the Row Key. In logs and historical data it can be useful to inverse the sort order. This allows us to take the 100 most recent additions to the Table Partition without having to do any manipulations like skipping or filtering Entities.

One way to do this, is to take the max date from the DateTime object and to subtract the current DateTime. Chances that collisions can occur are slim. But to make sure they don’t occur, I add a GUID to the end of the subtraction result.

public class Entity : TableEntity
{
  public Entity(string partitionKey)
  {
      PartitionKey = partitionKey;
      var inverseTimeKey = DateTime
                            .MaxValue
                            .Subtract(DateTime.UtcNow)
                            .TotalMilliseconds
                            .ToString(CultureInfo.InvariantCulture);
      RowKey = string.Format("{0}-{1}",
                              inverseTimeKey,
                              Guid.NewGuid());
  }

  public Entity()
  {
  }

  // ...  your properties
}

Trackbacks and Pingbacks:

  1. Using Time-based Partition Keys in #Azure Table Storage « Alexandre Brisebois - June 16, 2014

    […] a previous post about storing Azure Storage Table entities in descending order I combined a time-based key with a guid in order to create a unique key. This is practical when you […]

    Like

Leave a comment

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