1 | # Azure Cosmos DB client library for JavaScript/TypeScript
|
2 |
|
3 | [][npm]
|
4 | [](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=850&branchName=main)
|
5 |
|
6 | Azure Cosmos DB is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases. This package is intended for JavaScript/TypeScript applications to interact with **SQL API** databases and the JSON documents they contain:
|
7 |
|
8 | - Create Cosmos DB databases and modify their settings
|
9 | - Create and modify containers to store collections of JSON documents
|
10 | - Create, read, update, and delete the items (JSON documents) in your containers
|
11 | - Query the documents in your database using SQL-like syntax
|
12 |
|
13 | Key links:
|
14 |
|
15 | - [Package (npm)][npm]
|
16 | - [API reference documentation](https://docs.microsoft.com/javascript/api/@azure/cosmos/?view=azure-node-lates)
|
17 | - [Product documentation][cosmos_docs]
|
18 |
|
19 | ## Getting started
|
20 |
|
21 | ### Prerequisites
|
22 |
|
23 | #### Azure Subscription and Cosmos DB SQL API Account
|
24 |
|
25 | You must have an [Azure Subscription][azure_sub], and a [Cosmos DB account][cosmos_account] (SQL API) to use this package.
|
26 |
|
27 | If you need a Cosmos DB SQL API account, you can use the Azure [Cloud Shell][cloud_shell_bash] to create one with this Azure CLI command:
|
28 |
|
29 | ```Bash
|
30 | az cosmosdb create --resource-group <resource-group-name> --name <cosmos-database-account-name>
|
31 | ```
|
32 |
|
33 | Or you can create an account in the [Azure Portal](https://portal.azure.com/#create/microsoft.documentdb)
|
34 |
|
35 | #### NodeJS
|
36 |
|
37 | This package is distributed via [npm][npm] which comes preinstalled with [NodeJS](https://nodejs.org/en/) using an LTS version.
|
38 |
|
39 | #### CORS
|
40 |
|
41 | You need to set up [Cross-Origin Resource Sharing (CORS)](https://docs.microsoft.com/azure/cosmos-db/how-to-configure-cross-origin-resource-sharing) rules for your Cosmos DB account if you need to develop for browsers. Follow the instructions in the linked document to create new CORS rules for your Cosmos DB.
|
42 |
|
43 | ### Install this package
|
44 |
|
45 | ```Bash
|
46 | npm install @azure/cosmos
|
47 | ```
|
48 |
|
49 | ### Get Account Credentials
|
50 |
|
51 | You will need your Cosmos DB **Account Endpoint** and **Key**. You can find these in the [Azure Portal](https://portal.azure.com/#blade/hubsextension/browseresource/resourcetype/microsoft.documentdb%2fdatabaseaccounts) or use the [Azure CLI][azure_cli] snippet below. The snippet is formatted for the Bash shell.
|
52 |
|
53 | ```Bash
|
54 | az cosmosdb show --resource-group <your-resource-group> --name <your-account-name> --query documentEndpoint --output tsv
|
55 | az cosmosdb keys list --resource-group <your-resource-group> --name <your-account-name> --query primaryMasterKey --output tsv
|
56 | ```
|
57 |
|
58 | ### Create an instance of `CosmosClient`
|
59 |
|
60 | Interaction with Cosmos DB starts with an instance of the [CosmosClient](https://docs.microsoft.com/javascript/api/@azure/cosmos/cosmosclient?view=azure-node-latest) class
|
61 |
|
62 | ```js
|
63 | const { CosmosClient } = require("@azure/cosmos");
|
64 |
|
65 | const endpoint = "https://your-account.documents.azure.com";
|
66 | const key = "<database account masterkey>";
|
67 | const client = new CosmosClient({ endpoint, key });
|
68 |
|
69 | async function main() {
|
70 | // The rest of the README samples are designed to be pasted into this function body
|
71 | }
|
72 |
|
73 | main().catch((error) => {
|
74 | console.error(error);
|
75 | });
|
76 | ```
|
77 |
|
78 | For simplicity we have included the `key` and `endpoint` directly in the code but you will likely want to load these from a file not in source control using a project such as [dotenv](https://www.npmjs.com/package/dotenv) or loading from environment variables
|
79 |
|
80 | In production environments, secrets like keys should be stored in [Azure Key Vault](https://azure.microsoft.com/services/key-vault/)
|
81 |
|
82 | ## Key concepts
|
83 |
|
84 | Once you've initialized a [CosmosClient](https://docs.microsoft.com/javascript/api/@azure/cosmos/cosmosclient?view=azure-node-lates), you can interact with the primary resource types in Cosmos DB:
|
85 |
|
86 | - [Database](https://docs.microsoft.com/javascript/api/@azure/cosmos/database?view=azure-node-latest): A Cosmos DB account can contain multiple databases. When you create a database, you specify the API you'd like to use when interacting with its documents: SQL, MongoDB, Gremlin, Cassandra, or Azure Table. Use the [Database](https://docs.microsoft.com/javascript/api/@azure/cosmos/database?view=azure-node-latest) object to manage its containers.
|
87 |
|
88 | - [Container](https://docs.microsoft.com/javascript/api/@azure/cosmos/container?view=azure-node-latest): A container is a collection of JSON documents. You create (insert), read, update, and delete items in a container by using methods on the [Container](https://docs.microsoft.com/javascript/api/@azure/cosmos/container?view=azure-node-latest) object.
|
89 |
|
90 | - [Item](https://docs.microsoft.com/javascript/api/@azure/cosmos/item?view=azure-node-latest): An Item is a JSON document stored in a container. Each Item must include an `id` key with a value that uniquely identifies the item within the container. If you do not provide an `id`, the SDK will generate one automatically.
|
91 |
|
92 | For more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].
|
93 |
|
94 | ## Examples
|
95 |
|
96 | The following sections provide several code snippets covering some of the most common Cosmos DB tasks, including:
|
97 |
|
98 | - [Create a database](#create-a-database)
|
99 | - [Create a container](#create-a-container)
|
100 | - [Using Partition Keys](#using-partition-keys)
|
101 | - [Insert items](#insert-items)
|
102 | - [Query documents](#query-the-database)
|
103 | - [Read an item](#read-an-item)
|
104 | - [Delete an item](#delete-an-data)
|
105 | - [CRUD on Container with hierarchical partition key](#container-hierarchical-partition-key)
|
106 | ### Create a database
|
107 |
|
108 | After authenticating your [CosmosClient](https://docs.microsoft.com/javascript/api/@azure/cosmos/cosmosclient?view=azure-node-latest), you can work with any resource in the account. The code snippet below creates a NOSQL API database.
|
109 |
|
110 | ```js
|
111 | const { database } = await client.databases.createIfNotExists({ id: "Test Database" });
|
112 | console.log(database.id);
|
113 | ```
|
114 |
|
115 | ### Create a container
|
116 |
|
117 | This example creates a container with default settings
|
118 |
|
119 | ```js
|
120 | const { container } = await database.containers.createIfNotExists({ id: "Test Database" });
|
121 | console.log(container.id);
|
122 | ```
|
123 |
|
124 | ### Using Partition Keys
|
125 | This example shows various types of partition Keys supported.
|
126 | ```js
|
127 | await container.item("id", "1").read(); // string type
|
128 | await container.item("id", 2).read(); // number type
|
129 | await container.item("id", true).read(); // boolean type
|
130 | await container.item("id", {}).read(); // None type
|
131 | await container.item("id", undefined).read(); // None type
|
132 | await container.item("id", null).read(); // null type
|
133 | ```
|
134 |
|
135 | If the Partition Key consists of a single value, it could be supplied either as a literal value, or an array.
|
136 |
|
137 | ```js
|
138 | await container.item("id", "1").read();
|
139 | await container.item("id", ["1"]).read();
|
140 | ```
|
141 |
|
142 | If the Partition Key consists of more than one values, it should be supplied as an array.
|
143 | ```js
|
144 | await container.item("id", ["a", "b"]).read();
|
145 | await container.item("id", ["a", 2]).read();
|
146 | await container.item("id", [{}, {}]).read();
|
147 | await container.item("id", ["a", {}]).read();
|
148 | await container.item("id", [2, null]).read();
|
149 |
|
150 | ```
|
151 |
|
152 | ### Insert items
|
153 |
|
154 | To insert items into a container, pass an object containing your data to [Items.upsert](https://docs.microsoft.com/javascript/api/@azure/cosmos/items?view=azure-node-latest#upsert-t--requestoptions-). The Azure Cosmos DB service requires each item has an `id` key. If you do not provide one, the SDK will generate an `id` automatically.
|
155 |
|
156 | This example inserts several items into the container
|
157 |
|
158 | ```js
|
159 | const cities = [
|
160 | { id: "1", name: "Olympia", state: "WA", isCapitol: true },
|
161 | { id: "2", name: "Redmond", state: "WA", isCapitol: false },
|
162 | { id: "3", name: "Chicago", state: "IL", isCapitol: false }
|
163 | ];
|
164 | for (const city of cities) {
|
165 | await container.items.create(city);
|
166 | }
|
167 | ```
|
168 |
|
169 | ### Read an item
|
170 |
|
171 | To read a single item from a container, use [Item.read](https://docs.microsoft.com/javascript/api/@azure/cosmos/item?view=azure-node-latest#read-requestoptions-). This is a less expensive operation than using SQL to query by `id`.
|
172 |
|
173 | ```js
|
174 | await container.item("1", "1").read();
|
175 | ```
|
176 | ### CRUD on Container with hierarchical partition key
|
177 |
|
178 | Create a Container with hierarchical partition key
|
179 | ```js
|
180 | const containerDefinition = {
|
181 | id: "Test Database",
|
182 | partitionKey: {
|
183 | paths: ["/name", "/address/zip"],
|
184 | version: PartitionKeyDefinitionVersion.V2,
|
185 | kind: PartitionKeyKind.MultiHash,
|
186 | },
|
187 | }
|
188 | const { container } = await database.containers.createIfNotExists(containerDefinition);
|
189 | console.log(container.id);
|
190 | ```
|
191 | Insert an item with hierarchical partition key defined as - `["/name", "/address/zip"]`
|
192 | ```js
|
193 | const item = {
|
194 | id: "1",
|
195 | name: 'foo',
|
196 | address: {
|
197 | zip: 100
|
198 | },
|
199 | active: true
|
200 | }
|
201 | await container.items.create(item);
|
202 | ```
|
203 |
|
204 | To read a single item from a container with hierarchical partition key defined as - `["/name", "/address/zip"],`
|
205 | ```js
|
206 | await container.item("1", ["foo", 100]).read();
|
207 | ```
|
208 | Query an item with hierarchical partition key with hierarchical partition key defined as - `["/name", "/address/zip"],`
|
209 | ```js
|
210 | const { resources } = await container.items
|
211 | .query("SELECT * from c WHERE c.active = true", {
|
212 | partitionKey: ["foo", 100],
|
213 | })
|
214 | .fetchAll();
|
215 | for (const item of resources) {
|
216 | console.log(`${item.name}, ${item.address.zip} `);
|
217 | }
|
218 | ```
|
219 | ### Delete an item
|
220 |
|
221 | To delete items from a container, use [Item.delete](https://docs.microsoft.com/javascript/api/@azure/cosmos/item?view=azure-node-latest#delete-requestoptions-).
|
222 |
|
223 | ```js
|
224 | // Delete the first item returned by the query above
|
225 | await container.item("1").delete();
|
226 | ```
|
227 |
|
228 | ### Query the database
|
229 |
|
230 | A Cosmos DB SQL API database supports querying the items in a container with [Items.query](https://docs.microsoft.com/javascript/api/@azure/cosmos/items?view=azure-node-latest#query-string---sqlqueryspec--feedoptions-) using SQL-like syntax:
|
231 |
|
232 | ```js
|
233 | const { resources } = await container.items
|
234 | .query("SELECT * from c WHERE c.isCapitol = true")
|
235 | .fetchAll();
|
236 | for (const city of resources) {
|
237 | console.log(`${city.name}, ${city.state} is a capitol `);
|
238 | }
|
239 | ```
|
240 |
|
241 | Perform parameterized queries by passing an object containing the parameters and their values to [Items.query](https://docs.microsoft.com/javascript/api/@azure/cosmos/items?view=azure-node-latest#query-string---sqlqueryspec--feedoptions-):
|
242 |
|
243 | ```js
|
244 | const { resources } = await container.items
|
245 | .query({
|
246 | query: "SELECT * from c WHERE c.isCapitol = @isCapitol",
|
247 | parameters: [{ name: "@isCapitol", value: true }]
|
248 | })
|
249 | .fetchAll();
|
250 | for (const city of resources) {
|
251 | console.log(`${city.name}, ${city.state} is a capitol `);
|
252 | }
|
253 | ```
|
254 |
|
255 | For more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].
|
256 |
|
257 | ### Change Feed Pull Model
|
258 |
|
259 | Change feed can be fetched for a partition key, a feed range or an entire container.
|
260 |
|
261 | To process the change feed, create an instance of `ChangeFeedPullModelIterator`. When you initially create `ChangeFeedPullModelIterator`, you must specify a required `changeFeedStartFrom` value inside the `ChangeFeedIteratorOptions` which consists of both the starting position for reading changes and the resource(a partition key or a FeedRange) for which changes are to be fetched. You can optionally use `maxItemCount` in `ChangeFeedIteratorOptions` to set the maximum number of items received per page.
|
262 |
|
263 | Note: If no `changeFeedStartFrom` value is specified, then changefeed will be fetched for an entire container from Now().
|
264 |
|
265 | There are four starting positions for change feed:
|
266 |
|
267 | - `Beginning`
|
268 |
|
269 | ```js
|
270 | // Signals the iterator to read changefeed from the beginning of time.
|
271 | const options = {
|
272 | changeFeedStartFrom: ChangeFeedStartFrom.Beginning(),
|
273 | };
|
274 | const iterator = container.getChangeFeedIterator(options);
|
275 | ```
|
276 |
|
277 | - `Time`
|
278 |
|
279 | ```js
|
280 | // Signals the iterator to read changefeed from a particular point of time.
|
281 | const time = new Date("2023/09/11"); // some sample date
|
282 | const options = {
|
283 | changeFeedStartFrom: ChangeFeedStartFrom.Time(time),
|
284 | };
|
285 | ```
|
286 |
|
287 | - `Now`
|
288 |
|
289 | ```js
|
290 | // Signals the iterator to read changefeed from this moment onward.
|
291 | const options = {
|
292 | changeFeedStartFrom: ChangeFeedStartFrom.Now(),
|
293 | };
|
294 | ```
|
295 |
|
296 | - `Continuation`
|
297 |
|
298 | ```js
|
299 | // Signals the iterator to read changefeed from a saved point.
|
300 | const continuationToken = "some continuation token recieved from previous request";
|
301 | const options = {
|
302 | changeFeedStartFrom: ChangeFeedStartFrom.Continuation(continuationToken),
|
303 | };
|
304 | ```
|
305 |
|
306 | Here's an example of fetching change feed for a partition key
|
307 |
|
308 | ```js
|
309 | const partitionKey = "some-partition-Key-value";
|
310 | const options = {
|
311 | changeFeedStartFrom: ChangeFeedStartFrom.Beginning(partitionKey),
|
312 | };
|
313 |
|
314 | const iterator = container.items.getChangeFeedIterator(options);
|
315 |
|
316 | while (iterator.hasMoreResults) {
|
317 | const response = await iterator.readNext();
|
318 | // process this response
|
319 | }
|
320 | ```
|
321 |
|
322 | Because the change feed is effectively an infinite list of items that encompasses all future writes and updates, the value of `hasMoreResults` is always `true`. When you try to read the change feed and there are no new changes available, you receive a response with `NotModified` status.
|
323 |
|
324 | More detailed usage guidelines and examples of change feed can be found [here](https://learn.microsoft.com/azure/cosmos-db/nosql/change-feed-pull-model?tabs=javascript).
|
325 |
|
326 | ## Error Handling
|
327 |
|
328 | The SDK generates various types of errors that can occur during an operation.
|
329 |
|
330 | 1. `ErrorResponse` is thrown if the response of an operation returns an error code of >=400.
|
331 | 2. `TimeoutError` is thrown if Abort is called internally due to timeout.
|
332 | 3. `AbortError` is thrown if any user passed signal caused the abort.
|
333 | 4. `RestError` is thrown in case of failure of underlying system call due to network issues.
|
334 | 5. Errors generated by any devDependencies. For Eg. `@azure/identity` package could throw `CredentialUnavailableError`.
|
335 |
|
336 | Following is an example for handling errors of type `ErrorResponse`, `TimeoutError`, `AbortError`, and `RestError`.
|
337 |
|
338 | ```js
|
339 | try {
|
340 | // some code
|
341 | } catch (err) {
|
342 | if (err instanceof ErrorResponse) {
|
343 | // some specific error handling.
|
344 | } else if (err instanceof RestError) {
|
345 | // some specific error handling.
|
346 | }
|
347 | // handle other type of errors in similar way.
|
348 | else {
|
349 | // for any other error.
|
350 | }
|
351 | }
|
352 | ```
|
353 |
|
354 | It's important to properly handle these errors to ensure that your application can gracefully recover from any failures and continue functioning as expected. More details about some of these errors and their possible solutions can be found [here](https://learn.microsoft.com/azure/cosmos-db/nosql/conceptual-resilient-sdk-applications#should-my-application-retry-on-errors).
|
355 |
|
356 | ## Troubleshooting
|
357 |
|
358 | ### General
|
359 |
|
360 | When you interact with Cosmos DB errors returned by the service correspond to the same HTTP status codes returned for REST API requests:
|
361 |
|
362 | [HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]
|
363 |
|
364 | #### Conflicts
|
365 |
|
366 | For example, if you try to create an item using an `id` that's already in use in your Cosmos DB database, a `409` error is returned, indicating the conflict. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.
|
367 |
|
368 | ```js
|
369 | try {
|
370 | await containers.items.create({ id: "existing-item-id" });
|
371 | } catch (error) {
|
372 | if (error.code === 409) {
|
373 | console.log("There was a conflict with an existing item");
|
374 | }
|
375 | }
|
376 | ```
|
377 |
|
378 | ### Transpiling
|
379 |
|
380 | The Azure SDKs are designed to support ES5 JavaScript syntax and [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). If you need support for earlier JavaScript runtimes such as Internet Explorer or Node 6, you will need to transpile the SDK code as part of your build process.
|
381 |
|
382 | ### Handle transient errors with retries
|
383 |
|
384 | While working with Cosmos DB, you might encounter transient failures caused by [rate limits][cosmos_request_units] enforced by the service, or other transient problems like network outages. For information about handling these types of failures, see [Retry pattern][azure_pattern_retry] in the Cloud Design Patterns guide, and the related [Circuit Breaker pattern][azure_pattern_circuit_breaker].
|
385 |
|
386 | ### Logging
|
387 |
|
388 | Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`. While using `AZURE_LOG_LEVEL` make sure to set it before logging library is initialized.
|
389 | Ideally pass it through command line, if using libraries like `dotenv` make sure such libraries are initialized before logging library.
|
390 |
|
391 | ```javascript
|
392 | const { setLogLevel } = require("@azure/logger");
|
393 | setLogLevel("info");
|
394 | ```
|
395 |
|
396 | For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger).
|
397 |
|
398 | ### Diagnostics
|
399 |
|
400 | Cosmos Diagnostics feature provides enhanced insights into all your client operations. A CosmosDiagnostics object is added to response of all client operations. such as
|
401 | - Point look up operation reponse - `item.read()`, `container.create()`, `database.delete()`
|
402 | - Query operation reponse -`queryIterator.fetchAll()`,
|
403 | - Bulk and Batch operations -`item.batch()`.
|
404 | - Error/Exception response objects.
|
405 |
|
406 | A CosmosDiagnostics object is added to response of all client operations.
|
407 | There are 3 Cosmos Diagnostic levels, info, debug and debug-unsafe. Where only info is meant for production systems and debug and debug-unsafe are meant to be used during development and debugging, since they consume significantly higher resources. Cosmos Diagnostic level can be set in 2 ways
|
408 | - Programatically
|
409 | ```js
|
410 | const client = new CosmosClient({ endpoint, key, diagnosticLevel: CosmosDbDiagnosticLevel.debug });
|
411 | ```
|
412 | - Using environment variables. (Diagnostic level set by Environment variable has higher priority over setting it through client options.)
|
413 | ```bash
|
414 | export AZURE_COSMOSDB_DIAGNOSTICS_LEVEL="debug"
|
415 | ```
|
416 |
|
417 | Cosmos Diagnostic has three members
|
418 | - ClientSideRequestStatistics Type: Contains aggregates diagnostic details, including metadata lookups, retries, endpoints contacted, and request and response statistics like payload size and duration. (is always collected, can be used in production systems.)
|
419 |
|
420 | - DiagnosticNode: Is a tree-like structure that captures detailed diagnostic information. Similar to `har` recording present in browsers. This feature is disabled by default and is intended for debugging non-production environments only. (collected at diagnostic level debug and debug-unsafe)
|
421 |
|
422 | - ClientConfig: Captures essential information related to client's configuration settings during client initialization. (collected at diagnostic level debug and debug-unsafe)
|
423 |
|
424 | Please make sure to never set diagnostic level to `debug-unsafe` in production environment, since it this level `CosmosDiagnostics` captures request and response payloads and if you choose to log it (it is by default logged by @azure/logger at `verbose` level). These payloads might get captured in your log sinks.
|
425 |
|
426 | #### Consuming Diagnostics
|
427 |
|
428 | - Since `diagnostics` is added to all Response objects. You could programatically access `CosmosDiagnostic` as follows.
|
429 | ```js
|
430 | // For point look up operations
|
431 | const { container, diagnostics: containerCreateDiagnostic } =
|
432 | await database.containers.createIfNotExists({
|
433 | id: containerId,
|
434 | partitionKey: {
|
435 | paths: ["/key1"],
|
436 | },
|
437 | });
|
438 |
|
439 | // For Batch operations
|
440 | const operations: OperationInput[] = [
|
441 | {
|
442 | operationType: BulkOperationType.Create,
|
443 | resourceBody: { id: 'A', key: "A", school: "high" },
|
444 | },
|
445 | ];
|
446 | const response = await container.items.batch(operations, "A");
|
447 |
|
448 | // For query operations
|
449 | const queryIterator = container.items.query("select * from c");
|
450 | const { resources, diagnostics } = await queryIterator.fetchAll();
|
451 |
|
452 | // While error handling
|
453 | try {
|
454 | // Some operation that might fail
|
455 | } catch (err) {
|
456 | const diagnostics = err.diagnostics
|
457 | }
|
458 | ```
|
459 | - You could also log `diagnostics` using `@azure/logger`, diagnostic is always logged using `@azure/logger` at `verbose` level. So if you set Diagnostic level to `debug` or `debug-unsafe` and `@azure/logger` level to `verbose`, `diagnostics` will be logged.
|
460 | ## Next steps
|
461 |
|
462 | ### More sample code
|
463 |
|
464 | [Several samples][cosmos_samples] are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Cosmos DB:
|
465 |
|
466 | - Database Operations
|
467 | - Container Operations
|
468 | - Item Operations
|
469 | - Configuring Indexing
|
470 | - Reading a container Change Feed
|
471 | - Stored Procedures
|
472 | - Changing Database/Container throughput settings
|
473 | - Multi Region Write Operations
|
474 |
|
475 | ### Limitations
|
476 |
|
477 | Currently the features below are **not supported**. For alternatives options, check the **Workarounds** section below.
|
478 |
|
479 | ### Data Plane Limitations:
|
480 |
|
481 | * Queries with COUNT from a DISTINCT subquery
|
482 | * Direct TCP Mode access
|
483 | * Aggregate cross-partition queries, like sorting, counting, and distinct, don't support continuation tokens. Streamable queries, like SELECT \* FROM <table> WHERE <condition>, support continuation tokens. See the "Workaround" section for executing non-streamable queries without a continuation token.
|
484 | * Change Feed: Processor
|
485 | * Change Feed: Read multiple partitions key values
|
486 | * Change Feed pull model support for partial hierarchical partition keys [#27059](https://github.com/Azure/azure-sdk-for-js/issues/27059)
|
487 | * Cross-partition ORDER BY for mixed types
|
488 |
|
489 | ### Control Plane Limitations:
|
490 |
|
491 | * Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics
|
492 | * Create Geospatial Index
|
493 | * Update Autoscale throughput
|
494 |
|
495 | ## Workarounds
|
496 |
|
497 | ### Continuation token for cross partitions queries
|
498 | You can achieve cross partition queries with continuation token support by using
|
499 | [Side car pattern](https://github.com/Azure-Samples/Cosmosdb-query-sidecar).
|
500 | This pattern can also enable applications to be composed of heterogeneous components and technologies.
|
501 |
|
502 | ### Executing non-stremable cross-partition query
|
503 |
|
504 | To execute non-streamable queries without the use of continuation tokens, you can create a query iterator with the required query specification and options. The following sample code demonstrates how to use a query iterator to fetch all results without the need for a continuation token:
|
505 |
|
506 | ```javascript
|
507 | const querySpec = {
|
508 | query: "SELECT c.status, COUNT(c.id) AS count FROM c GROUP BY c.status",
|
509 | };
|
510 | const queryOptions = {
|
511 | maxItemCount: 10, // maximum number of items to return per page
|
512 | enableCrossPartitionQuery: true,
|
513 | };
|
514 | const querIterator = await container.items.query(querySpec, queryOptions);
|
515 | while (querIterator.hasMoreResults()) {
|
516 | const { resources: result } = await querIterator.fetchNext();
|
517 | //Do something with result
|
518 | }
|
519 | ```
|
520 |
|
521 | This approach can also be used for streamable queries.
|
522 |
|
523 | ### Control Plane operations
|
524 | Typically, you can use [Azure Portal](https://portal.azure.com/), [Azure Cosmos DB Resource Provider REST API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider), [Azure CLI](https://docs.microsoft.com/cli/azure/azure-cli-reference-for-cosmos-db) or [PowerShell](https://docs.microsoft.com/azure/cosmos-db/manage-with-powershell) for the control plane unsupported limitations.
|
525 |
|
526 |
|
527 | ### Additional documentation
|
528 |
|
529 | For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.
|
530 |
|
531 | ## Useful links
|
532 |
|
533 | - [Welcome to Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/community)
|
534 | - [Quick start](https://docs.microsoft.com/azure/cosmos-db/sql-api-nodejs-get-started)
|
535 | - [Tutorial](https://docs.microsoft.com/azure/cosmos-db/sql-api-nodejs-application)
|
536 | - [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cosmosdb/cosmos/samples)
|
537 | - [Introduction to Resource Model of Azure Cosmos DB Service](https://docs.microsoft.com/azure/cosmos-db/sql-api-resources)
|
538 | - [Introduction to SQL API of Azure Cosmos DB Service](https://docs.microsoft.com/azure/cosmos-db/sql-api-sql-query)
|
539 | - [Partitioning](https://docs.microsoft.com/azure/cosmos-db/sql-api-partition-data)
|
540 | - [API Documentation](https://docs.microsoft.com/javascript/api/%40azure/cosmos/?view=azure-node-latest)
|
541 |
|
542 | ## Contributing
|
543 |
|
544 | If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.
|
545 |
|
546 | 
|
547 |
|
548 |
|
549 |
|
550 | [azure_cli]: https://docs.microsoft.com/cli/azure
|
551 | [azure_pattern_circuit_breaker]: https://docs.microsoft.com/azure/architecture/patterns/circuit-breaker
|
552 | [azure_pattern_retry]: https://docs.microsoft.com/azure/architecture/patterns/retry
|
553 | [azure_portal]: https://portal.azure.com
|
554 | [azure_sub]: https://azure.microsoft.com/free/
|
555 | [cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview
|
556 | [cloud_shell_bash]: https://shell.azure.com/bash
|
557 | [cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account
|
558 | [cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview
|
559 | [cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers
|
560 | [cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases
|
561 | [cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/
|
562 | [cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb
|
563 | [cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items
|
564 | [cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units
|
565 | [cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items
|
566 | [cosmos_samples]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cosmosdb/cosmos/samples
|
567 | [cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query
|
568 | [cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live
|
569 | [npm]: https://www.npmjs.com/package/@azure/cosmos
|