Toni Parviainen
Toni Parviainen

Reputation: 2387

How to query different type of documents in parallel?

I'm using Cosmos DB (DocumentDB) and .NET Core. Let's say I have to completely different documents (simplified example):

public class Market // DocumentType = "market"
{
    public string Id {get;set;}
    public string Description {get; set;}
}

public class City // DocumentTyupe = "city"
{
    public string Id {get;set;}
    public string Name {get; set;}
}

To get all of those I can run two queries one by one:

var markets = client.CreateDocumentQuery<Market>()
.Where(x => x.DocumentType == "market").ToList()

var cities = client.CreateDocumentQuery<City>()
.Where(x => x.DocumentType == "city").ToList()

What is the recommended approach to execute both queries in parallel? So I'm thinking something like this:

var markets = QueryMarkets(); // returns Task    
var cities = QueryCities(); // returns Task
Task.WhenAll(markets, cities); //execute in parallel

Is there something built into that I could benefit from?

Upvotes: 2

Views: 550

Answers (1)

Jesse Carter
Jesse Carter

Reputation: 21207

There is no built in functionality with Cosmos that would allow you to execute multiple queries in parallel from the server side. Your approach to awaiting them in parallel using Task.WhenAll in your client application is the correct one.

The only other alternative would be to create a custom Stored Procedure that could aggregate the results of more than one query but based on the example that you're showing I don't think there would be any benefits for either speed or RU consumption to go down that route.

Upvotes: 3

Related Questions