首页 > 解决方案 > 如何使用查询从 cosmos db 中获取最大 id 值

问题描述

我想从 cosmos DB 中获取 id 的最大值。下面的代码运行良好,直到 cosmos DB 包含的文档少于 1000。如果超过,它总是给出 999 作为最大值。

尝试在 FeedOptions 中添加 MaxItemCount=-1。

public async Task<int> GetMaxId()
        {
            try
            {
                var option = new FeedOptions { EnableCrossPartitionQuery = true ,MaxItemCount=-1};
                // SQL
                var familiesSqlQuery = client.CreateDocumentQuery(cosmosConnector,
                    "SELECT value max(c.id) FROM c", option).AsDocumentQuery();
                var val = await familiesSqlQuery.ExecuteNextAsync();

                var s = val.FirstOrDefault();
                return int.Parse(s.ToString());
            }
            catch
            {
                throw;
            }
        }

标签: c#sqlazureazure-cosmosdb

解决方案


实现您想要的可靠方法如下:

public async Task<int> GetMaxId()
{
    try
    {
        var maxValue = 0;
        var option = new FeedOptions { EnableCrossPartitionQuery = true };
        // SQL
        var familiesSqlQuery = client.CreateDocumentQuery(cosmosConnector,
            "SELECT c.id FROM c", option).AsDocumentQuery();

        while(familiesSqlQuery.HasMoreResults)
        {
            var ids = await familiesSqlQuery.ExecuteNextAsync();
            var maxIdInBatch = ids.Select(int.Parse).Max();
            if(maxIdInBatch > maxValue)
            {
                maxValue = maxIdInBatch;
            }           
        }

        return maxValue;
    }
    catch
    {
        throw;
    }
}

出现这种情况的原因是您的 RU 不会因单个调用而耗尽,因为您将对所有结果进行分页。这将需要更长的时间,但它将是可靠和准确的。


推荐阅读