Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check if DocumentDB object exists

In Microsoft examples I saw two ways to check if DocumentDb object like Database, DocumentCollection, Document etc. exists :

First is by creating a query:

Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEnumerable().FirstOrDefault();
if (db == null)
    {
        await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
    }

The second one is by using "try catch" block:

    try
    {
       await this.client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode == HttpStatusCode.NotFound)
        {
           await this.client.CreateDatabaseAsync(new Database { Id = databaseName });
         }
         else
         {
             throw;
          }
    }

What is the correct way to do this procedure in terms of performance?

like image 374
Strelnikov Lev Avatar asked Mar 08 '17 14:03

Strelnikov Lev


People also ask

Is Cosmos DB a DocumentDB?

Azure Cosmos DB is the next big leap in globally distributed, at scale, cloud databases. As a DocumentDB customer, you now have access to the new breakthrough system and capabilities offered by Azure Cosmos DB.

What is Upsert in Cosmos DB?

Upserts a Document as an asychronous operation in the Azure Cosmos DB service. UpsertDocumentAsync(Uri, Object, RequestOptions, Boolean, CancellationToken) Upserts a document as an asynchronous operation in the Azure Cosmos DB service.


2 Answers

You should use the new CreateDatabaseIfNotExistsAsync in the DocumentDB SDK instead of both these approaches, if that's what you're trying to do.

In terms of server resources (request units), a ReadDocumentAsync is slightly more lightweight than CreateDatabaseQuery, so you should use that when possible.

like image 105
Aravind Krishna R. Avatar answered Nov 15 '22 21:11

Aravind Krishna R.


I've just seen the try/catch example in one of the Microsoft provided sample project and it got me baffled, as it is plain wrong: you don't use try/catch for control flow.

Never.

This is just bad code. The new SDK provides CreateDatabaseIfNotExistsAsync which I can only hope doesn't just hide this shit. In older lib just use the query approach, unless you want to get shouted at by whoever is going to review the code.

like image 35
Michal Ja Avatar answered Nov 15 '22 20:11

Michal Ja