Storing Windows Azure Storage Table Entities in Descending Order

March 1, 2013 — Leave a 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
}
About these ads

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s