Home > Software engineering >  ToListAsync() vs AsDocumentQuery()
ToListAsync() vs AsDocumentQuery()

Time:11-14

I just read this section which shows this example:

IDocumentQuery<dynamic> query = client.CreateDocumentQuery(
    UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), 
    "SELECT * FROM c WHERE c.city = 'Seattle'", 
    new FeedOptions 
    { 
        PartitionKey = new PartitionKey("Washington")
    }).AsDocumentQuery();
while (query.HasMoreResults) 
{
    foreach(Document document in await queryable.ExecuteNextAsync())
    {
        // Iterate through documents
    }
}

In our project's codebase, we're doing something like this instead:

var invoiceList = await CreateDocumentQuery(companyId).Where(i => i.InvoiceId == invoiceId).ToListAsync();

where CreateDocumentQuery() returns an IOrderedQueryable<Invoice>.

Is it bad to use ToListAsync()? When should I use ToListAsync() vs AsDocumentQuery()/ExecuteNextAsync()?

CodePudding user response:

AsDocumentQuery let's you consume the query at your own pace and yield if you need to paginate (returning the Continuation Token).

ToListAsync drains the query completely in one go.

It depends on your use case, which pattern fits better. The recommendation that I see here: https://learn.microsoft.com/azure/cosmos-db/nosql/troubleshoot-query-performance#common-sdk-issues is: " Be sure to drain the query completely."

ToListAsync would drain it completely, AsDocumentQuery would too as long as you consume it until HasMoreResults is false (like in your snippet).

  • Related