Search code examples
c#azureazure-storage

How to retrieve latest record using RowKey or Timestamp in Azure Table storage


Tricky part is RowKey is string which is having value like Mon Nov 14 12:26:42 2016

I tried query using Timestamp like

var lowerlimit = DateTime.UtcNow; // its should be nearer to table timestamp data.
            TableQuery<TemperatureEntity> query2 = new TableQuery<TemperatureEntity>().Where(TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual,lowerlimit));
            var test = table.ExecuteQuery(query2);

MyEntity.cs

  public class MyEntity : TableEntity
    {
        public MyEntity(string partitionKey, string rowKey)
        {
            this.PartitionKey = partitionKey;
            this.RowKey = rowKey;
        }

        public MyEntity() { }

        public Int64 DevideId { get; set; }

        public string RowKey { get; set; }
    }

//below query gives full data Program.cs

// Retrieve the storage account from the connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "TemperatureData" table.
            CloudTable table = tableClient.GetTableReference("TemperatureData");

            // retrive data
            TableQuery<TemperatureEntity> query = new TableQuery<TemperatureEntity>();
            var data = table.ExecuteQuery(query);

enter image description here


Solution

  • Azure Table Service doesn't support Order By functionality, thus with the current setup only option for you is to download all entities and sort them reverse chrnologically on the client side. This obviously is not an optimal solution when the number of entities in the table become large.

    Other option (which would require you to redesign the application) would be to convert the date/time value in reverse ticks:

    var rowKey = (DateTime.MaxValue.Ticks - DateTimeValueForRowKey.Ticks).ToString("d19")
    

    This will ensure that the latest entries are added to the top of the table instead of at the bottom of the table. To fetch the latest entry, you would just have to take 1st entity from the table.