Azure Cosmos DB Core (SQL) API Overview
Azure Cosmos DB is a globally distributed, multi-model database service that enables you to rapidly create and query document, key-value, and graph databases, all while benefiting from the seamless, automatic, and transparent scalability and throughput that production workloads depend on.
Key Features
- Globally Distributed: Deploy your data to any Azure region with a single API call. Achieve multi-region write capabilities for high availability and low latency.
- Multi-Model: Support for various data models including document (Core/SQL API), key-value, graph, and column-family.
- Guaranteed Throughput: Provisioned throughput with guaranteed low latency and high availability.
- Elastic Scalability: Scale throughput and storage elastically and independently.
- Multiple Consistency Models: Offers five well-defined consistency levels (Strong, Bounded Staleness, Session, Consistent Prefix, Eventual) to balance consistency and availability.
- Comprehensive SDKs: Available for various programming languages including .NET, Java, Node.js, Python, and JavaScript.
Getting Started with Core (SQL) API
The Core (SQL) API is the default API for Azure Cosmos DB, providing a powerful JSON document database with schema-agnostic data indexing and rich query capabilities using a familiar SQL syntax.
Creating a Cosmos DB Account
Before you can create any resources, you need to create an Azure Cosmos DB account. You can do this through the Azure portal, Azure CLI, or PowerShell.
Creating a Database and Container
Within your Cosmos DB account, you'll create databases and containers. Containers are where your data resides. Each container can hold JSON documents.
Tip: Containers are horizontally partitioned and can store an effectively unlimited amount of data.
Example: Inserting a Document
Here's a simple example using the Node.js SDK to insert a document into a container:
// Import the CosmosClient class
const { CosmosClient } = require("@azure/cosmos");
// Your Cosmos DB connection string
const connectionString = "AccountEndpoint=https://.documents.azure.com:443/;AccountKey=;";
const client = new CosmosClient(connectionString);
async function createDocument() {
const databaseId = "mydatabase";
const containerId = "mycontainer";
const { database } = await client.databases.createIfNotExists({ id: databaseId });
const { container } = await database.containers.createIfNotExists({ id: containerId });
const newItem = {
id: "document1",
name: "Example Document",
category: "Testing",
tags: ["sample", "document"]
};
const { resource: createdItem } = await container.items.create(newItem);
console.log(`Created item with id: ${createdItem.id}`);
}
createDocument().catch(error => {
console.error("Error:", error);
});
Querying Data
You can query your documents using SQL-like queries. For example, to find all documents in the 'Testing' category:
SELECT * FROM c WHERE c.category = "Testing"