UNPKG

15 kBMarkdownView Raw
1# Azure Cosmos DB client library for JavaScript/TypeScript
2
3[![latest npm badge](https://img.shields.io/npm/v/%40azure%2Fcosmos/latest.svg)][npm]
4[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/js/js%20-%20cosmosdb%20-%20ci?branchName=main)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=850&branchName=main)
5
6Azure 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
13Key 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
25You must have an [Azure Subscription][azure_sub], and a [Cosmos DB account][cosmos_account] (SQL API) to use this package.
26
27If 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
30az cosmosdb create --resource-group <resource-group-name> --name <cosmos-database-account-name>
31```
32
33Or you can create an account in the [Azure Portal](https://portal.azure.com/#create/microsoft.documentdb)
34
35#### NodeJS
36
37This package is distributed via [npm][npm] which comes preinstalled with [NodeJS](https://nodejs.org/en/). You should be using Node v10 or above.
38
39#### CORS
40
41You 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
46npm install @azure/cosmos
47```
48
49### Get Account Credentials
50
51You 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
54az cosmosdb show --resource-group <your-resource-group> --name <your-account-name> --query documentEndpoint --output tsv
55az 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
60Interaction 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
63const { CosmosClient } = require("@azure/cosmos");
64
65const endpoint = "https://your-account.documents.azure.com";
66const key = "<database account masterkey>";
67const client = new CosmosClient({ endpoint, key });
68
69async function main() {
70 // The rest of the README samples are designed to be pasted into this function body
71}
72
73main().catch((error) => {
74 console.error(error);
75});
76```
77
78For 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
80In production environments, secrets like keys should be stored in [Azure Key Vault](https://azure.microsoft.com/services/key-vault/)
81
82## Key concepts
83
84Once 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
92For more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].
93
94## Examples
95
96The 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- [Insert items](#insert-items)
101- [Query documents](#query-the-database)
102- [Read an item](#read-an-item)
103- [Delete an item](#delete-an-data)
104
105### Create a database
106
107After 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 SQL API database.
108
109```js
110const { database } = await client.databases.createIfNotExists({ id: "Test Database" });
111console.log(database.id);
112```
113
114### Create a container
115
116This example creates a container with default settings
117
118```js
119const { container } = await database.containers.createIfNotExists({ id: "Test Database" });
120console.log(container.id);
121```
122
123### Insert items
124
125To 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 Cosmos DB service requires each item has an `id` key. If you do not provide one, the SDK will generate an `id` automatically.
126
127This example inserts several items into the container
128
129```js
130const cities = [
131 { id: "1", name: "Olympia", state: "WA", isCapitol: true },
132 { id: "2", name: "Redmond", state: "WA", isCapitol: false },
133 { id: "3", name: "Chicago", state: "IL", isCapitol: false }
134];
135for (const city of cities) {
136 container.items.create(city);
137}
138```
139
140### Read an item
141
142To 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`.
143
144```js
145await container.item("1").read();
146```
147
148### Delete an item
149
150To delete items from a container, use [Item.delete](https://docs.microsoft.com/javascript/api/@azure/cosmos/item?view=azure-node-latest#delete-requestoptions-).
151
152```js
153// Delete the first item returned by the query above
154await container.item("1").delete();
155```
156
157### Query the database
158
159A 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:
160
161```js
162const { resources } = await container.items
163 .query("SELECT * from c WHERE c.isCapitol = true")
164 .fetchAll();
165for (const city of resources) {
166 console.log(`${city.name}, ${city.state} is a capitol `);
167}
168```
169
170Perform 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-):
171
172```js
173const { resources } = await container.items
174 .query({
175 query: "SELECT * from c WHERE c.isCapitol = @isCapitol",
176 parameters: [{ name: "@isCapitol", value: true }]
177 })
178 .fetchAll();
179for (const city of resources) {
180 console.log(`${city.name}, ${city.state} is a capitol `);
181}
182```
183
184For more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].
185
186## Troubleshooting
187
188### General
189
190When you interact with Cosmos DB errors returned by the service correspond to the same HTTP status codes returned for REST API requests:
191
192[HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]
193
194#### Conflicts
195
196For 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.
197
198```js
199try {
200 await containers.items.create({ id: "existing-item-id" });
201} catch (error) {
202 if (error.code === 409) {
203 console.log("There was a conflict with an existing item");
204 }
205}
206```
207
208### Transpiling
209
210The 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.
211
212### Handle transient errors with retries
213
214While 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].
215
216## Next steps
217
218### More sample code
219
220[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:
221
222- Database Operations
223- Container Operations
224- Item Operations
225- Configuring Indexing
226- Reading a container Change Feed
227- Stored Procedures
228- Changing Database/Container throughput settings
229- Multi Region Write Operations
230
231### Limitations
232
233Currently the features below are **not supported**. For alternatives options, check the **Workarounds** section below.
234
235### Data Plane Limitations:
236
237* Queries with COUNT from a DISTINCT subquery​
238* Direct TCP Mode access​
239* Continuation token for cross partitions queries
240* Change Feed: Processor
241* Change Feed: Read multiple partitions key values
242* Change Feed: Read specific time
243* Change Feed: Read from the beginning
244* Change Feed: Pull model
245* Cross-partition ORDER BY for mixed types
246
247### Control Plane Limitations:
248
249* Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics​
250* Create Geospatial Index
251* Update Autoscale throughput
252
253## Workarounds
254
255### Continuation token for cross partitions queries
256You can achieve cross partition queries with continuation token support by using
257[Side car pattern](https://github.com/Azure-Samples/Cosmosdb-query-sidecar).
258This pattern can also enable applications to be composed of heterogeneous components and technologies.
259
260### Control Plane operations
261Typically, 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.
262
263
264### Additional documentation
265
266For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.
267
268## Useful links
269
270- [Welcome to Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/community)
271- [Quick start](https://docs.microsoft.com/azure/cosmos-db/sql-api-nodejs-get-started)
272- [Tutorial](https://docs.microsoft.com/azure/cosmos-db/sql-api-nodejs-application)
273- [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cosmosdb/cosmos/samples)
274- [Introduction to Resource Model of Azure Cosmos DB Service](https://docs.microsoft.com/azure/cosmos-db/sql-api-resources)
275- [Introduction to SQL API of Azure Cosmos DB Service](https://docs.microsoft.com/azure/cosmos-db/sql-api-sql-query)
276- [Partitioning](https://docs.microsoft.com/azure/cosmos-db/sql-api-partition-data)
277- [API Documentation](https://docs.microsoft.com/javascript/api/%40azure/cosmos/?view=azure-node-latest)
278
279## Contributing
280
281If 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.
282
283![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcosmosdb%2Fcosmos%2FREADME.png)
284
285<!-- LINKS -->
286
287[azure_cli]: https://docs.microsoft.com/cli/azure
288[azure_pattern_circuit_breaker]: https://docs.microsoft.com/azure/architecture/patterns/circuit-breaker
289[azure_pattern_retry]: https://docs.microsoft.com/azure/architecture/patterns/retry
290[azure_portal]: https://portal.azure.com
291[azure_sub]: https://azure.microsoft.com/free/
292[cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview
293[cloud_shell_bash]: https://shell.azure.com/bash
294[cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account
295[cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview
296[cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers
297[cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases
298[cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/
299[cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb
300[cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items
301[cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units
302[cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items
303[cosmos_samples]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cosmosdb/cosmos/samples
304[cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query
305[cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live
306[npm]: https://www.npmjs.com/package/@azure/cosmos