如何使用Azure表存储中的RowKey或Timestamp检索最新记录

Neo*_*Neo 12 c# azure azure-storage

棘手的部分是RowKeystring由具有类似值Mon Nov 14 12:26:42 2016

我试过使用 Timestamp

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);
Run Code Online (Sandbox Code Playgroud)

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; }
    }
Run Code Online (Sandbox Code Playgroud)

//下面的查询提供了完整的数据 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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Viv*_*ier 22

新,

如果您需要在分区中拥有最新条目,则使用字符串日期时间为行键不是一个好方法,因为表存储基于行键按升序存储实体.

如果在当前点您可以更改行键的值,请使用DateTime.UtcNow.Ticks:

var invertedTimeKey = DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks
Run Code Online (Sandbox Code Playgroud)

使用这种方法,在查询表时,您将能够获得与最新表对应的1个条目.

如果您无法更改行键的值,则必须检索分区中的所有条目,这意味着将所有条目加载到内存中,然后使用Timestamp对它们进行排序以检索最后一个条目.如果你有很多条目,这绝对不是一个好方法.

var lastResult = results.OrderByDescending(r => r.Timestamp).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • 请查看下面的Gaurav答案,因为该代码段正确指定了ToString格式d19,该数字以零填充。RowKey存储为字符串,因此按字符串排序,这意味着“ 2”大于“ 1582”。 (2认同)
  • 以下是描述解决方案的MS文档的链接https://docs.microsoft.com/en-us/azure/cosmos-db/table-storage-design-guide#log-tail-pattern (2认同)

Gau*_*tri 10

Azure表服务不支持Order By功能,因此当前设置的唯一选项是下载所有实体并在客户端进行chrnological反向排序.当表中的实体数量变大时,这显然不是最佳解决方案.

其他选项(需要您重新设计应用程序)将以反向刻度转换日期/时间值:

var rowKey = (DateTime.MaxValue.Ticks - DateTimeValueForRowKey.Ticks).ToString("d19")
Run Code Online (Sandbox Code Playgroud)

这将确保将最新条目添加到表的顶部而不是表的底部.要获取最新条目,您只需从表中获取第一个实体.

  • 例如,DateTimeValueForRowKey 的值将是 DateTime.UtcNow.Ticks (2认同)