简体   繁体   中英

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

I want to get the maximum of the id from the cosmos DB. Below code is working well until cosmos DB contains documents less than 1000. If it exceeds it is always giving 999 as the max value.

Tried adding MaxItemCount=-1 in the FeedOptions.

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;
            }
        }

A reliable way to achieve what you want is the following:

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;
    }
}

The reason why that's the case is that your RUs won't be exhausted for a single call because you will be paginating through all the results. It will take longer but it will be reliable and accurate.

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