首页 > 解决方案 > Azure 表:如何编写范围查询来过滤分区键

问题描述

我将当前的 UTC 日期四舍五入到最接近的分钟并将其转换为刻度以将结果保存为PartitionKeyAzure 表存储。我想运行一个范围查询来获取代码中的特定分区键范围。我正在使用 C#,但显然不支持以下 LINQ 操作。

var tableQuery = cloudTable.CreateQuery<Log>().Where(x => long.Parse(x.PartitionKey) <= ticks); 

投掷

System.NotSupportedException: 'The expression (Parse([10007].PartitionKey) <= 637224147600000000) is not supported.'

我也尝试过String.Compare(),但它也不起作用。那么,如何在 C# 中编写过滤查询以获取小于或等于给定刻度的记录?请注意,以这种方式选择分区键,以便记录可以自然地按时间降序排序。

标签: c#azurelinqazure-storageazure-table-storage

解决方案


下面是我用来获取数据的示例。根据您的情况尝试以下查询。我认为它应该工作。

public async Task<Advertisement> GetAdvertisementBy(string id, string user)
    {
        List<Advertisement> list = new List<Advertisement>();
        // Initialize the continuation token to null to start from the beginning of the table.
        TableContinuationToken continuationToken = null;
        var filter1 = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, user);
        var filter3 = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id);
        var combine = TableQuery.CombineFilters(filter1, TableOperators.And, filter3);
        TableQuery<Advertisement> query = new TableQuery<Advertisement>().Where(combine);
        do
        {
            // Retrieve a segment (up to 1,000 entities).
            TableQuerySegment<Advertisement> tableQueryResult = await base.Table.ExecuteQuerySegmentedAsync(query, continuationToken);
            // Assign the new continuation token to tell the service where to
            // continue on the next iteration (or null if it has reached the end).
            continuationToken = tableQueryResult.ContinuationToken;
            list.AddRange(tableQueryResult.Results);
            // Loop until a null continuation token is received, indicating the end of the table.
        } while (continuationToken != null);

        return list.FirstOrDefault();
    }

推荐阅读