Azure Cosmos DB APIs
This document provides an overview and detailed reference for interacting with Azure Cosmos DB services through various APIs.
Introduction to Azure Cosmos DB
Azure Cosmos DB is a globally distributed, multi-model database service. It offers a powerful platform for building modern applications that require low-latency data access, high availability, and massive scalability. Cosmos DB supports several data models, including document, key-value, graph, and column-family, and provides multiple APIs to access and manipulate your data.
Supported APIs
Azure Cosmos DB is designed to be interoperable with existing databases and applications. It offers the following APIs:
- SQL (Core) API: The native API for Azure Cosmos DB, offering rich query capabilities using a JSON document model.
- MongoDB API: Offers compatibility with MongoDB applications, allowing you to leverage existing tools and drivers.
- Cassandra API: Provides a Cassandra-compatible interface for NoSQL workloads.
- Azure Table Storage API: Designed for applications using Azure Table Storage, offering a key-value store.
- Gremlin API: Supports graph database scenarios using the Apache TinkerPop Gremlin language.
Key API Operations and Concepts
Regardless of the API used, several core concepts are fundamental to interacting with Azure Cosmos DB:
- Database Accounts: The top-level resource in Cosmos DB.
- Databases: A container for collections (or equivalent objects depending on API).
- Collections/Containers: The basic unit of data storage and throughput in Cosmos DB.
- Documents/Items: The individual data entities stored within a collection.
- Partition Key: A property of a document that determines its physical location for scalability.
- Throughput: Measured in Request Units (RUs) per second, defining the performance capacity.
API Reference Tables
SQL (Core) API Reference
The SQL API provides a RESTful interface for managing resources and querying data. You can interact with it directly using HTTP requests or through SDKs.
Operation | HTTP Method | Path | Description | SDK Example |
---|---|---|---|---|
Create Document | POST | /dbs/{db_id}/colls/{coll_id}/docs | Adds a new document to a collection. | View |
Read Document | GET | /dbs/{db_id}/colls/{coll_id}/docs/{doc_id} | Retrieves a specific document. | View |
Query Documents | POST | /dbs/{db_id}/colls/{coll_id}/docs | Executes a SQL query against a collection. | View |
Create Collection | POST | /dbs/{db_id}/colls | Creates a new collection within a database. | View |
MongoDB API Reference
Connect to your Cosmos DB account using any MongoDB driver or tool.
Operation | MongoDB Method | Description | Driver Example |
---|---|---|---|
Insert Document | insertOne / insertMany |
Adds documents to a collection. | View |
Find Documents | find |
Queries documents based on specified criteria. | View |
Create Collection | createCollection |
Creates a new collection. | View |
SDKs and Tools
Azure Cosmos DB provides robust SDKs for various programming languages and integrates with popular tools:
- SDKs: .NET, Java, Node.js, Python, Go, C++
- Tools: Azure portal, Azure CLI, Azure PowerShell, Cosmos DB Data Migration Tool, Azure Data Studio.
SDK Examples
SQL API: Create Document (Conceptual .NET)
var client = new CosmosClient("YOUR_COSMOS_DB_CONNECTION_STRING");
var database = client.GetDatabase("myDatabase");
var container = database.GetContainer("myContainer");
var newItem = new { id = "item1", category = "gear", name = "hiking boots", price = 120.00 };
var response = await container.CreateItemAsync(newItem, new PartitionKey(newItem.category));
Console.WriteLine($"Created item with ID: {response.Resource.id}");
SQL API: Read Document (Conceptual .NET)
var itemResponse = await container.ReadItemAsync<dynamic>("item1", new PartitionKey("gear"));
Console.WriteLine($"Read item: {itemResponse.Resource}");
SQL API: Query Documents (Conceptual .NET)
var query = new QueryDefinition("SELECT * FROM c WHERE c.price > 100");
var resultSet = container.GetItemQueryIterator<dynamic>(query);
while (resultSet.HasMoreResults)
{
var response = await resultSet.ReadNextAsync();
foreach (var item in response)
{
Console.WriteLine($"Found item: {item.name}");
}
}
SQL API: Create Collection (Conceptual .NET)
await database.CreateContainerAsync("newContainer", "/category");
Console.WriteLine("Container 'newContainer' created.");
MongoDB API: Insert Document (Conceptual Node.js)
const { MongoClient } = require('mongodb');
const uri = "mongodb://YOUR_COSMOS_DB_ACCOUNT_NAME:YOUR_COSMOS_DB_KEY@YOUR_COSMOS_DB_ACCOUNT_NAME.documents.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@CosmosDB@";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("myMongoDatabase");
const collection = database.collection("myMongoCollection");
const doc = { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" };
const result = await collection.insertOne(doc);
console.log(`${result.insertedCount} document(s) were inserted.`);
} finally {
await client.close();
}
}
run().catch(console.dir);
MongoDB API: Find Documents (Conceptual Node.js)
const { MongoClient } = require('mongodb');
// ... client setup ...
async function run() {
try {
await client.connect();
const database = client.db("myMongoDatabase");
const collection = database.collection("myMongoCollection");
const cursor = collection.find({ status: "A" });
await cursor.forEach(doc => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
MongoDB API: Create Collection (Conceptual Node.js)
const { MongoClient } = require('mongodb');
// ... client setup ...
async function run() {
try {
await client.connect();
const database = client.db("myMongoDatabase");
await database.createCollection("newMongoCollection");
console.log("Collection 'newMongoCollection' created.");
} finally {
await client.close();
}
}
run().catch(console.dir);
For comprehensive API details, specific SDK usage, and advanced configurations, please refer to the official Azure Cosmos DB documentation.