简体   繁体   中英

How to query the most recent n records from Azure Table Storage?

I am using the following query in c# .net:

TableQuery<MyType> query = new TableQuery<MyType>().Take(50);

This works in grabbing 50 records, but I want to grab the most recent (descending) records from the table. I have looked at other answers, but none were concise or working.

What is the most efficient way to grab n most recent records from an Azure Table Storage entity? Please provide a concise answer with a working code example.

Unfortunately there is no easy way to fetch latest records from Azure Table Storage as it does not allow you to sort the records on attributes. Records in Azure Table Storage are always sorted by PartitionKey and then by RowKey within a partition.

One way to fix this problem is to specify the PartitionKey value as reverse chronological ticks (something like (DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks).ToString("d20") ) so that whenever you add an entity, it will be prepended (ie added to the top of the table). Now when you do the query and fetch "x" number of records, you will always the most recent records.

Other option is to fetch all entities and do the sorting on the client side. This is highly inefficient and is generally not recommended. This solution might work if you have very small number of entities (less than 1000 for example) in your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM