Home > Software design >  How to count list items in a Cosmos DB field?
How to count list items in a Cosmos DB field?

Time:03-16

I am working on a feature where one part is to count how many items we have on a list. The thing is that this list is a field in Cosmos DB entry. So, let me describe it in more detail.

The entry (link group) that we contain in our dB is next:

{
    "id": "d238dff6-39f3-4dfe-9c40-a87ee1c81fc8",
    "name": "Link group 1",
    "links": [
        "9b354a31-8c15-451f-b90a-3400305dde9a",
        "f5ba7488-3ab2-468a-88e1-d2ac66bc9bc6",
        "5ffe355f-bc2a-4774-a1f5-26ce285dd6a4"
    ],
    ...
}

I tried to get all items and then call the Count() method. This is now working, but I want to optimize it more since I don't want to load all data in memory and then call Count() method.

So the question is: How to count the number of links in one particular link group without loading all links in memory?

CodePudding user response:

If you are using C# a good way to do this is to make the Cosmos query a .CountAsync() opposed to getting the items in memory and then performing a .Count() E.g:

 var totalCountQuery = await _cosmosDbService.GetQueryable<ObjectType>();
 totalCountQuery = totalCountQuery.Where(x => Condition).Select(x => x.Links);

 var totalCount = await totalCountQuery.CountAsync();

These are a part of a nice package called CosmosLinqExtensions. https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.linq.cosmoslinqextensions?view=azure-dotnet

Hopefully this helps :)

CodePudding user response:

If you want to find out how many links are there for each link item, you can make use of ARRAY_LENGTH function.

Your query would be something like:

SELECT r.name, ARRAY_LENGTH(r.links) linksCount FROM Root r

which will produce a response like:

[
    {
        "name": "Link group 1",
        "linksCount": 3
    },
    {
        "name": "Link group 2",
        "linksCount": 2
    }
]
  • Related