Home > Mobile >  What is the advised way to query CosmosDB using list of Ids
What is the advised way to query CosmosDB using list of Ids

Time:05-04

My partition Key use to be one value. Now it's a list of users. How do I use a list for partition keys? Here is what I have for my query.

const string queryText = @"SELECT *
                                FROM    c
                                WHERE   ARRAY_CONTAINS(@Ids, c.UserID) = true
                                -- LastModified
                                AND DateTimeFromParts(StringToNumber(SUBSTRING(c.LastModified, 0, 4))
                                    ,StringToNumber(SUBSTRING(c.LastModified, 5, 2))
                                    ,StringToNumber(SUBSTRING(c.LastModified, 8, 2)))
                                -- Current Date/Time minus 60 days
                                    >= DateTimeAdd('day', -60, GetCurrentDateTime())
                                ORDER BY c.LastModified DESC
                                ";
        var query = new QueryDefinition(queryText);

        ids?.Add(LoggedInUser.Id);
        query.WithParameter("@Ids", ids?.ToArray());

var returnList = new List<CosmosItemModel>();
        var requestOptions = new QueryRequestOptions { PartitionKey = new PartitionKey(loggedInUserId) };
        var feedIterator = Container.GetItemQueryIterator<CosmosItemModel>(queryDefinition, null, requestOptions);
        while (feedIterator.HasMoreResults)
            foreach (var item in await feedIterator.ReadNextAsync())
                returnList.Add(item);

But when I use LoggedInUser for mu partition key I only get documents for that user not the list of users from my query. How can I use my list of ids for partition keys?

CodePudding user response:

Microsoft advises against querying across multiple partitions if you have large containers because of the RU cost.

Beyond that you can just add an OR to the query.

SELECT * FROM c WHERE c.partitionKey = @partitionA OR c.partitionKey = @partitionB

And as David Makogon pointed out, ARRAY_CONTAINS probably isn't what you're looking for.

  • Related