6 View Cosmos DB SQL Query - adamhockemeyer/Azure-Functions---CosmosDB-ResourceToken-Broker GitHub Wiki

Bonus Content

View Generated SQL


As you interact more with Cosmos DB, you may find it useful to see what the actual query (SQL in this case) was that was created magically and sent to Cosmos DB. When you create a lambda (i.e. p => p.Breed == "Goldendoodle") and really start to chain these and add in additional logic, it would be nice to see what the actual query being generated is, so that you may be able to go back and further refine your query to improve performance.

There are a couple ways to get the SQL generated for your query.

.ToString()


You can simply call the .ToString() method on a query, to get the SQL that is generates.

  • Pros - It's simple and easy
  • Cons - If you want to see several statements, you need to hack up your code just to see the sql.

Fiddler Http Trace


You can use Fiddler when developing locally to see the query that is getting set to Cosmos DB.

  • Pros - It's simple, easy, and you don't have to hack up your code
  • Cons - The connection protocol on the Cosmos DB client sdk must be set to Protocol.Https (temporarily at least), and you need to install another piece of software.

Once you have Fiddler open, you can then view the request that was made, and click on the "JSON" tab to view the query that was generated and sent to Cosmos DB.

Fiddler Cosmos DB Query

For reference, the following repository method and lambda were used to generate the sql above:

var results = await repo.GetItemAsync<Dog>(p => p.Breed == breed);

You may notice that only the WHERE clause for Breed here, but type Type clause is actually built into the repository, so that we query Cosmos DB for the specific type of document that we are looking for. This is essentially what the TypedDocument<T> class that the Dog class in this example provides for us.

⚠️ **GitHub.com Fallback** ⚠️