Quickstart: Use Node.js to connect and query data from Azure Cosmos DB SQL API account
APPLIES TO:
SQL API
In this quickstart, you create and manage an Azure Cosmos DB SQL API account from the Azure portal, and by using a Node.js app cloned from GitHub. Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with global distribution and horizontal scale capabilities.
Walkthrough video
Watch this video for a complete walkthrough of the content in this article.
Prerequisites
- An Azure account with an active subscription. Create one for free. Or try Azure Cosmos DB for free without an Azure subscription. You can also use the Azure Cosmos DB Emulator with a URI of
https://localhost:8081
and the keyC2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
. - Node.js 6.0.0+.
- Git.
Create an Azure Cosmos account
For this quickstart purpose, you can use the try Azure Cosmos DB for free option to create an Azure Cosmos account.
Navigate to the try Azure Cosmos DB for free page.
Choose the SQL API account and select Create. Sign-in using your Microsoft account.
After the sign-in is successful, your Azure Cosmos account should be ready. Select Open in the Azure portal to open the newly created account.
The "try Azure Cosmos DB for free" option doesn't require an Azure subscription and it offers you an Azure Cosmos account for a limited period of 30 days. If you want to use the Azure Cosmos account for a longer period, you should instead create the account within your Azure subscription.
Add a container
You can now use the Data Explorer tool in the Azure portal to create a database and container.
Select Data Explorer > New Container.
The Add Container area is displayed on the far right, you may need to scroll right to see it.
In the Add container page, enter the settings for the new container.
Setting Suggested value Description Database ID Tasks Enter Tasks as the name for the new database. Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?
, or a trailing space. Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. This option also helps with cost savings.Throughput 400 Leave the throughput at 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later. Container ID Items Enter Items as the name for your new container. Container IDs have the same character requirements as database names. Partition key /category The sample described in this article uses /category as the partition key. In addition to the preceding settings, you can optionally add Unique keys for the container. Let's leave the field empty in this example. Unique keys provide developers with the ability to add a layer of data integrity to the database. By creating a unique key policy while creating a container, you ensure the uniqueness of one or more values per partition key. To learn more, refer to the Unique keys in Azure Cosmos DB article.
Select OK. The Data Explorer displays the new database and container.
Add sample data
You can now add data to your new container using Data Explorer.
From the Data Explorer, expand the Tasks database, expand the Items container. Select Items, and then select New Item.
Now add a document to the container with the following structure.
{ "id": "1", "category": "personal", "name": "groceries", "description": "Pick up apples and strawberries.", "isComplete": false }
Once you've added the json to the Documents tab, select Save.
Create and save one more document where you insert a unique value for the
id
property, and change the other properties as you see fit. Your new documents can have any structure you want as Azure Cosmos DB doesn't impose any schema on your data.
Query your data
You can use queries in Data Explorer to retrieve and filter your data.
At the top of the Items tab in Data Explorer, review the default query
SELECT * FROM c
. This query retrieves and displays all documents from the container ordered by ID.To change the query, select Edit Filter, replace the default query with
ORDER BY c._ts DESC
, and then select Apply Filter.The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.
If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.
Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. You also use the portal to scale throughput, get keys and connection strings, and review metrics and SLAs for your Azure Cosmos DB account.
Clone the sample application
Now let's clone a Node.js app from GitHub, set the connection string, and run it.
Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.
git clone https://github.com/Azure-Samples/azure-cosmos-db-sql-api-nodejs-getting-started.git
Review the code
This step is optional. If you're interested in learning how the Azure Cosmos database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to Update your connection string.
If you're familiar with the previous version of the SQL JavaScript SDK, you may be used to seeing the terms collection and document. Because Azure Cosmos DB supports multiple API models, version 2.0+ of the JavaScript SDK uses the generic terms container, which may be a collection, graph, or table, and item to describe the content of the container.
The Cosmos DB JavaScript SDK is called "@azure/cosmos" and can be installed from npm...
npm install @azure/cosmos
The following snippets are all taken from the app.js file.
The
CosmosClient
is imported from the@azure/cosmos
npm package.const CosmosClient = require("@azure/cosmos").CosmosClient;
A new
CosmosClient
object is initialized.const client = new CosmosClient({ endpoint, key });
Select the "Tasks" database.
const database = client.database(databaseId);
Select the "Items" container/collection.
const container = database.container(containerId);
Select all the items in the "Items" container.
// query to return all items const querySpec = { query: "SELECT * from c" }; const { resources: items } = await container.items .query(querySpec) .fetchAll();
Create a new item
const { resource: createdItem } = await container.items.create(newItem);
Update an item
const { id, category } = createdItem; createdItem.isComplete = true; const { resource: updatedItem } = await container .item(id, category) .replace(createdItem);
Delete an item
const { resource: result } = await container.item(id, category).delete();
Note
In both the "update" and "delete" methods, the item has to be selected from the database by calling container.item()
. The two parameters passed in are the id of the item and the item's partition key. In this case, the parition key is the value of the "category" field.
Update your connection string
Now go back to the Azure portal to get the connection string details of your Azure Cosmos account. Copy the connection string into the app so that it can connect to your database.
In your Azure Cosmos DB account in the Azure portal, select Keys from the left navigation, and then select Read-write Keys. Use the copy buttons on the right side of the screen to copy the URI and Primary Key into the app.js file in the next step.
In Open the config.js file.
Copy your URI value from the portal (using the copy button) and make it the value of the endpoint key in config.js.
endpoint: "<Your Azure Cosmos account URI>"
Then copy your PRIMARY KEY value from the portal and make it the value of the
config.key
in config.js. You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.key: "<Your Azure Cosmos account key>"
Run the app
Run
npm install
in a terminal to install the "@azure/cosmos" npm packageRun
node app.js
in a terminal to start your node application.The two items that you created earlier in this quickstart are listed out. A new item is created. The "isComplete" flag on that item is updated to "true" and then finally, the item is deleted.
You can continue to experiment with this sample application or go back to Data Explorer, modify, and work with your data.
Review SLAs in the Azure portal
The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.
To review metrics and SLAs:
Select Metrics in your Cosmos DB account's navigation menu.
Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.
Review the metrics on the other tabs.
Next steps
In this quickstart, you've learned how to create an Azure Cosmos DB account, create a container using the Data Explorer, and run a Node.js app. You can now import additional data to your Azure Cosmos DB account.