<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nishant Middha on Medium]]></title>
        <description><![CDATA[Stories by Nishant Middha on Medium]]></description>
        <link>https://medium.com/@middha.nishant173?source=rss-26bad6f59380------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zUFdlDPWc_DK-rLz55aksQ@2x.jpeg</url>
            <title>Stories by Nishant Middha on Medium</title>
            <link>https://medium.com/@middha.nishant173?source=rss-26bad6f59380------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:56:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@middha.nishant173/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Improve query performance with Azure CosmosDB Java SDK v4]]></title>
            <link>https://medium.com/@middha.nishant173/improve-query-performance-with-azure-cosmosdb-java-sdk-v4-db1fc54cb484?source=rss-26bad6f59380------2</link>
            <guid isPermaLink="false">https://medium.com/p/db1fc54cb484</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[azure-services]]></category>
            <category><![CDATA[cosmos-sdk]]></category>
            <category><![CDATA[cosmosdb]]></category>
            <dc:creator><![CDATA[Nishant Middha]]></dc:creator>
            <pubDate>Sun, 21 Nov 2021 05:51:33 GMT</pubDate>
            <atom:updated>2021-11-21T05:51:33.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*kH6JK-OHeJ1HHo7Q" /><figcaption>Source: Microsoft</figcaption></figure><p>This article is intended to give you a brief introduction to Azure Cosmos DB and make you understand ways in which we can improve query performance which at the end will impact the overall performance of your application.</p><h3>What is Azure Cosmos DB?</h3><p>Azure Cosmos DB is a globally distributed <em>NoSQL</em> database service on Microsoft Azure cloud. It provides single-digit milliseconds response time, high availability, and auto-instant scalability options that can fulfill application needs. <strong>It is a multi-model store that can act as a document store, key-value store, wide-column store, and graph store.</strong></p><p>Azure Cosmos DB exposes multiple database APIs such as <em>Core SQL, Cassandra API, MongoDB API, Gremlin API, and Table API</em>. We can build apps on these APIs using SDKs exposed for popular languages such as .NET, Java, Python, and Node JS.</p><h3>Query Performance</h3><p>There are various client-side optimizations that can be done to improve application performance.</p><ol><li>Choosing the <em>connectivity mode</em></li><li>Tuning “<em>maxItemCount</em>” for single-partition query</li><li>Tuning “<em>maxDegreeOfParallelism</em>” for parallel cross-partition query</li><li>Caching <em>Query Execution Plan</em></li><li>Specify “<em>PartitionKey</em>” explicitly</li></ol><h4>Connectivity Mode</h4><p>There are two connectivity modes present to connect to Cosmos DB.</p><ol><li><em>Gateway</em> Mode</li><li><em>Direct</em> Mode</li></ol><p>Gateway mode provides connectivity using HTTPS whereas Direct Mode uses TCP. The former one involves an additional hop i.e Gateway server every time a request is made to Cosmos DB. If your corporate network has strict firewalls and the application has access to a limited number of socket connections then go for gateway mode otherwise it is preferred to use direct mode because the application can connect directly to the cosmos backend replicas.</p><h4>Tuning “<em>maxItemCount</em>” for single-partition query</h4><p>A query that is routed to a specific physical partition based on the partition key filter present in the query is called a <em>single-partition </em>query.</p><p>Within each partition, the query might make one or more round trips to server to fetch results depending on the query complexity, configured page size, response payload size, provisioned throughput of the container, and system allocated timeout. Each round trip to the server will return no more than the number of items in “<em>maxItemCount</em>”. <strong>By default, results are returned in chunks of 100 items or 1 MB, whichever limit is hit first.</strong></p><p>For a single partition query “<em>maxItemCount</em>” can have a significant impact on end-to-end query time by limiting the number of round trips to the server especially for the queries with large result sets. <strong>It is recommended to set it to -1 to get a large number of items in a round trip.</strong></p><pre>// Build CosmosAsyncClient</pre><pre>CosmosAsyncClient client = new CosmosClientBuilder()         .endpoint(HOSTNAME)<br>.key(MASTERKEY)<br>.consistencyLevel(CONSISTENCY)         .directMode(directConnectionConfig,gatewayConnectionConfig)         .buildAsyncClient();</pre><pre>// Initialize instance of CosmosQueryRequestOptions<br>CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();<br>queryOptions.setMaxItemCount(-1)</pre><pre>// Query<br>client.queryItems(query, queryOptions, Test.class)</pre><h4>Tuning “maxDegreeOfParallelism” for parallel cross-partition query</h4><p>A query that does not have a filter present against the partition key gets fan out to all the physical partitions is called a <em>cross-partition</em> query. If the partition key is specified in the query using IN keyword then it is routed to the relevant physical partitions.</p><p>Parallel cross-partition queries allow you to perform low latency queries.</p><p>“<em>maxDegreeOfParallelism</em>” denotes the maximum number of simultaneous network connections to the container’s partitions.</p><ol><li>“<em>maxDegreeOfParallelism</em>”=-1 means Cosmos DB handles the degree of parallelism.</li><li>“<em>maxDegreeOfParallelism</em>”=0 means there is a single network connection and will query the partition one by one in series.</li><li>“<em>maxDegreeOfParallelism</em>” &gt;0 means multiple partitions will be queried in parallel.</li></ol><p><em>Note</em>: For cross-partition queries, setting the “<em>maxItemCount</em>” option to -1 can result in unmanageable data set therefore it is recommended to set its value to some large but finite value, perhaps 1000, to reduce latency.</p><pre>// Build CosmosAsyncClient</pre><pre>CosmosAsyncClient client = new CosmosClientBuilder()         .endpoint(HOSTNAME)<br>.key(MASTERKEY)<br>.consistencyLevel(CONSISTENCY)         .directMode(directConnectionConfig,gatewayConnectionConfig)         .buildAsyncClient();</pre><pre>// Initialize instance of CosmosQueryRequestOptions<br>CosmosQueryRequestOptions queryOptions = new CosmosQueryRequestOptions();<br>queryOptions.setMaxItemCount(1000)<br>queryOptions.setMaxDegreeOfParallelism(100)</pre><pre>// Query<br>client.queryItems(query, queryOptions, Test.class)</pre><h4>Caching Query Execution Plan</h4><p>Below mentioned are the steps involved while executing a query using direct mode.</p><ol><li>Parse the query to check for syntax errors.</li><li>Make a call to gateway server to fetch the query plan.</li><li>Check for partition key filter in the query to determine whether it is single partition query or cross partition query.</li><li>Execute query in series or parallel based on “maxDegreeOfParallelism” option.</li><li>Aggregate results on the client side.</li></ol><p>Query plan retrieval is an overhead for every query therefore to avoid this query plan can be cached for queries with filters and are scoped to a single partition. For version 4.20.0 or above caching is enabled by default and for older versions we need to set this VM option “-DCOSMOS.QUERYPLAN_CACHING_ENABLED” equal to true.</p><p>The key for the cached query plan is the SQL query string. <strong>We need to make sure that the query is parametrized. </strong>For example,</p><pre>SELECT * FROM c WHERE c.employerId = @employerId and c.employeeName= @employeeName</pre><p>Query plan cache look up for the above query will be cache hit always.</p><pre>SELECT * FROM c WHERE c.employerId = &quot;employerId&quot; and c.employeeName= &quot;employeeName&quot;</pre><p>Query plan cache look up for the above query will be cache miss except for the combination “employerId” and “employeeName”.</p><p><em>Note: “</em>employerId<em>” </em>is the partition key in both the queries.</p><h3>Specify “<em>PartitionKey</em>” explicitly</h3><p>Specifying the partition key value explicitly improves the query performance.</p><pre>// Insert item</pre><pre>container.createItem(employee, new PartitionKey(employee.getEmployerId()), new CosmosItemRequestOptions());</pre><pre>// Read item by id</pre><pre>container.readItem(id, new PartitionKey(employerId), Employee.class)</pre><pre>// Replace item</pre><pre>container.replaceItem(employee, employee.getId(), new PartitionKey(employee.getEmployerId()), new CosmosItemRequestOptions());</pre><pre>// Delete item</pre><pre>container.deleteItem(id, new PartitionKey(employerId), new CosmosItemRequestOptions());</pre><p>Thank you for reading. Keep learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db1fc54cb484" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>