簡體   English   中英

如何使用查詢從cosmos db獲取最大id值

[英]How to Get max of id value from the cosmos db using query

我想從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;
            }
        }

實現您想要的可靠方法如下:

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不會因為一次調用而耗盡,因為你將對所有結果進行分頁。 這將花費更長的時間,但它將是可靠和准確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM