Showing rows in reverse chronological order using Windows Azure Table Storage a.k.a order by descending

We can set the RowKey to be a fixed length string equivalent of DateTime.MaxValue.Ticks -  DateTime.UtcNow.Ticks. This allows the RowKey to sort the items by an offsetted time from newest items to older items.

string rowKeyToUse = string.Format("{0:D19}", 
DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks);

This works because when you move ahead in time, DateTime.UtcNow.Ticks increases in value -

thereby the difference between max value and this value decreases - hence these rows will go to the top.

let us assume that a blog can be rated from 0-5 and we want to ensure that blogs are listed such that they are sorted by  (Rating  in desc order, Created time in desc order).   This means that they are storted first by rating, and then sorted within each rating by the created time.   Here we can set the row key to <Rating>+<Ticks to force items to be sorted from newest to older items>. So taking the same example as above, in the two blogs above, let us assume blog1 was rated 5 and blog2 was rated 1. Having the Rating precede the ticks will allow blog1 to be listed before blog2 despite the fact that blog2 was blogged after blog1

This is not very clear. What they are saying here is that, we may want to order by something else descending (not just time). Say we want it to order by rating desc, then by time desc. What we need to do is:

DateTime.MaxValue.Ticks - (Rating +  DateTime.UtcNow.Ticks)

This will basically increase the right side value by rating in addition to the current time. Hence the rows will be ordered by those rows which have highest rating + which are newest in time.

Just thought a more detailed explanation would make sense for all readers.

Another thing to note is that even though the PartitionKey and RowKey columns are present for all entities, it must always be a discrete column in your entity class. So, if you set the RowKey correctly, but there is no column in your entity class which internally uses RowKey, it will never get saved.

This essentially means having a property like this:

        public long ReverseTickValue
        {
            get
            {
                long result = 0;
                long.TryParse(this.RowKey, out result);
                return result;
            }
            set
            {
                this.RowKey = value.ToString();
            }
        }



Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

The ridiculous interview experience