### get command examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of the get command, including with and without partition key. ```bash # Get document CS > get user1 # Get with partition key CS > get user1 --partition-key user1 ``` -------------------------------- ### Install dependencies and run NodeJS sample Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/readpreference-global-distribution For the NodeJS sample, these commands install required packages and start the application. The application will fail initially due to an invalid connection string. ```bash cd mean npm install node index.js ``` -------------------------------- ### Install Cassandra Go driver with go get Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/manage-data-go Import the `github.com/apache/cassandra-gocql-driver/v2` package from Go. This installs the client library required for connecting to the Cassandra account. ```bash go get github.com/apache/cassandra-gocql-driver/v2 ``` -------------------------------- ### Start the Kafka-Cosmos Cassandra integration pipeline Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/kafka-connect Starts all services defined in the docker-compose file. This may take a while to download and start the containers; it is a one-time setup. ```shell docker-compose --project-name kafka-cosmos-cassandra up --build ``` -------------------------------- ### mkdb examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of creating a database with default settings, provisioned throughput, and autoscale. ```bash # Create database with default settings CS > mkdb mydb # Create database with provisioned throughput CS > mkdb mydb --throughput 400 # Create database with autoscale CS > mkdb mydb --autoscale 4000 ``` -------------------------------- ### create command examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of the create command, including simple, nested, and array documents. ```bash # Create simple document CS > create item {"id": "user1", "name": "Alice"} # Create nested document CS > create item {"id": "user2", "name": "Bob", "address": {"city": "Seattle", "country": "USA"}} # Create with array CS > create item {"id": "user3", "name": "Charlie", "tags": ["vip", "premium"]} ``` -------------------------------- ### Start the sample application Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/access-data-spring-data-app Run the built JAR file to start the Spring Data Cassandra application. ```shell java -jar target/spring-data-cassandra-on-azure-0.1.0-SNAPSHOT.jar ``` -------------------------------- ### cd - Change directory examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of navigating to a database, container, going back one level, and navigating to root. ```bash # Navigate to a database CS > cd mydb # Navigate to a container CS > cd users # Go back one level CS > cd .. # Navigate to root CS > cd / CS > ``` -------------------------------- ### mkcon examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of creating a container with various options: partition key, throughput, autoscale, TTL, and unique key. ```bash # Create container with partition key CS > mkcon users -pk /id # Create with provisioned throughput CS > mkcon users -pk /id --throughput 400 # Create with autoscale CS > mkcon users -pk /id --autoscale 4000 # Create with TTL CS > mkcon users -pk /id --ttl 86400 # Create with unique key CS > mkcon users -pk /id --unique-key /email ``` -------------------------------- ### Install azidentity package Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-go Install the azidentity package using go install if not already installed. ```bash go install github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### Create virtual environment and install packages (Linux/macOS) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/how-to-python-get-started Creates a virtual environment and installs the packages from requirements.txt. Use this on Linux or macOS. ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install azidentity library using go install Source: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-go Installs the Azure Identity client library for Go to support token authentication. ```Bash go install github.com/Azure/azure-sdk-for-go/sdk/azidentity ``` -------------------------------- ### Install project dependencies with npm install Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-typescript Installs the project dependencies. Run this after generating the .env file and before compiling and running the sample. ```console npm install ``` -------------------------------- ### version example: display version Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Example of using version. The output shows 'Azure Cosmos DB Shell 1.0.213-preview'. ```bash CS > version Azure Cosmos DB Shell 1.0.213-preview ``` -------------------------------- ### Install the kit with Gemini CLI Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/agent-kit/setup Command to install the kit as a Gemini extension. ```bash gemini extensions install https://github.com/AzureCosmosDB/cosmosdb-agent-kit ``` -------------------------------- ### Install the kit with GitHub Copilot CLI Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/agent-kit/setup Commands to add the plugin marketplace and install the kit for GitHub Copilot CLI. ```text /plugin marketplace add AzureCosmosDB/cosmosdb-agent-kit /plugin install cosmosdb@cosmosdb-agent-kit ``` -------------------------------- ### CLI startup options examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of launching the shell with Entra ID authentication, managed identity, and explicit ARM context. ```bash # Launch with Entra ID authentication cosmosdbshell --connect https://myaccount.documents.azure.com:443/ --connect-tenant= # Launch with managed identity cosmosdbshell --connect https://myaccount.documents.azure.com:443/ --connect-managed-identity= # Launch with explicit ARM context cosmosdbshell --connect https://myaccount.documents.azure.com:443/ --connect-tenant= --connect-subscription= --connect-resource-group= ``` -------------------------------- ### Clone and install the complete sample Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/langchain-javascript-get-started Use these Bash commands to clone the GitHub sample repository, change into its directory, and install dependencies. After setting the required environment variables, run `node get-started.js` to execute the complete application. ```bash git clone https://github.com/AzureCosmosDB/langchainjs-cosmosdb-rag-quickstart.git cd langchainjs-cosmosdb-rag-quickstart npm install ``` -------------------------------- ### Example JSON response for getting a user Source: https://learn.microsoft.com/en-us/azure/cosmos-db/tutorial-springboot-azure-kubernetes-service This JSON snippet shows an example response from the GET /users/{email} endpoint, containing the user's details. ```json { "email": "john.doe@foobar.com", "firstName": "John", "lastName": "Doe", "city": "Dallas" } ``` -------------------------------- ### Install azcosmos client library using go install Source: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-go Installs the Azure Cosmos DB client library package for Go into your environment. ```Bash go install github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos ``` -------------------------------- ### Install azcosmos package Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-go Install the azcosmos package using go install if not already installed. ```bash go install github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos ``` -------------------------------- ### echo example: output text Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Example of using echo to display a message. The output is shown as 'Starting operations...'. ```bash CS > echo "Starting operations..." Starting operations... ``` -------------------------------- ### rm command examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of the rm command, including with and without partition key. ```bash # Delete document CS > rm user1 # Delete with partition key CS > rm user1 --partition-key user1 ``` -------------------------------- ### Install CQLSH on Unix/Linux/Mac Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/support Installs Java, imports the Baltimore CyberTrust root certificate, and installs Cassandra 3.11.13 to get CQLSH. This is required before connecting to Azure Cosmos DB for Apache Cassandra. ```bash # Install default-jre and default-jdk sudo apt install default-jre sudo apt-get update sudo apt install default-jdk # Import the Baltimore CyberTrust root certificate: curl https://cacert.omniroot.com/bc2025.crt > bc2025.crt keytool -importcert -alias bc2025ca -file bc2025.crt # Install the Cassandra libraries in order to get CQLSH: echo "deb https://downloads.apache.org/cassandra/debian 311x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add - sudo apt-get update sudo apt-get install cassandra=3.11.13 ``` -------------------------------- ### Run the application: node get-started.js Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/langchain-javascript-get-started Run this command to execute the application. Ensure get-started.js, sample-data.txt, and package.json with "type": "module" are present. ```Bash node get-started.js ``` -------------------------------- ### Initialize Go module and install dependencies Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-vector-store-go Changes to the project directory and initializes the Go module with the name 'vector-search-quickstart'. ```bash cd vector-search-quickstart go mod init vector-search-quickstart ``` -------------------------------- ### Java application starting point without comments Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/manage-data-java-v4-sdk The Java application after removing comments and console output. This is the starting point for the remainder of the guide. ```java package quickstart; public class App { public static void main(String[] args) { } } ``` -------------------------------- ### Install PostgreSQL extension with create_extension() function Source: https://learn.microsoft.com/en-us/azure/cosmos-db/postgresql/reference-extensions Use the create_extension() function when CREATE EXTENSION fails with a permission denied error. This example installs the PostGIS extension. ```sql SELECT create_extension('postgis'); ``` -------------------------------- ### Run the sample Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-dotnet Run the sample project using the .NET CLI. ```console dotnet run --project nosql-create-index-dotnet.csproj ``` -------------------------------- ### Install aztables package Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-go Install the `aztables` package using `go install` if not already installed. The package is available as `github.com/Azure/azure-sdk-for-go/sdk/data/aztables`. ```bash go install github.com/Azure/azure-sdk-for-go/sdk/data/aztables ``` -------------------------------- ### Initialize project with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-nodejs Initialize the project using the `cosmos-db-nosql-nodejs-quickstart` template. ```bash azd init --template cosmos-db-nosql-nodejs-quickstart ``` -------------------------------- ### Emulator command examples for each parameter Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-windows-arguments Example commands for each emulator parameter, including startup, help, status, shutdown, data path, ports, API endpoints, key file, reset, traces, SSL certificate, and direct ports. Each example shows the exact command to run. ```powershell Microsoft.Azure.Cosmos.Emulator.exe ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /? ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /GetStatus ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /Shutdown ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /DataPath=E:\SomeDataFolder ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /Port=65000 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /ComputePort=65100 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=3.2 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=3.6 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=4.0 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /MongoPort=65200 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableCassandraEndpoint ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /CassandraPort=65300 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableGremlinEndpoint ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /GremlinPort=65400 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /EnableTableEndpoint ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /TablePort=65500 ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /KeyFile=D:\Keys\keyfile ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /ResetDataPath ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /StartTraces ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /StopTraces ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /StartWprTraces ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /StopWprTraces ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /FailOnSslCertificateNameMismatch ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /GenCert ``` ```powershell Microsoft.Azure.Cosmos.Emulator.exe /DirectPorts:65600,65700 ``` -------------------------------- ### Azure PowerShell: Install required module version Source: https://learn.microsoft.com/en-us/azure/cosmos-db/periodic-backup-update-storage-redundancy Install the Az.CosmosDB module version 1.4.0 or higher using the `Install-Module` cmdlet. This is required for the Azure PowerShell commands in this guide. ```powershell $parameters = @{ Name = "Az.CosmosDB" RequiredVersion = "1.4.0" } Install-Module @parameters ``` -------------------------------- ### Install Azure Cosmos DB Python SDK in virtual environment Source: https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-python-get-started Use this command to install the Azure Cosmos DB for NoSQL Python SDK in a virtual environment. This is part of the project setup for the tutorial. ```bash pip install azure-cosmos ``` -------------------------------- ### query command examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of the query command, including filtering, partition key, limit, aggregate, and join queries. ```bash # Query all documents CS > query "SELECT * FROM c" # Query with filter CS > query "SELECT * FROM c WHERE c.status = 'active'" # Query with partition key (faster) CS > query "SELECT * FROM c WHERE c.id = 'user1'" --partition-key user1 # Query with limit CS > query "SELECT TOP 10 * FROM c" # Aggregate query CS > query "SELECT c.status, COUNT(*) as count FROM c GROUP BY c.status" # Join query CS > query "SELECT c.id, c.name, o.orderId FROM c JOIN o IN c.orders" ``` -------------------------------- ### Change to the .NET sample directory Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-dotnet Navigate to the .NET sample directory for the create-index sample. ```bash cd nosql-create-index-dotnet ``` -------------------------------- ### Get-CosmosDbEmulatorStatus with AlternativeInstallLocation Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-windows-arguments Gets the status of an emulator installed in the D:\SomeFolder\AzureCosmosDBEmulator folder by passing the AlternativeInstallLocation parameter via a splatting variable. ```powershell @parameters = { AlternativeInstallLocation = "D:\SomeFolder\AzureCosmosDBEmulator" } Get-CosmosDbEmulatorStatus @parameters ``` -------------------------------- ### Start Change Feed Processor with handleChanges Source: https://learn.microsoft.com/en-us/azure/cosmos-db/change-feed-processor Build and start a ChangeFeedProcessor instance using handleChanges() and the provided hostName, feedContainer, leaseContainer, and options. The start() method is asynchronous and uses Schedulers.boundedElastic(). ```Java logger.info("Start Change Feed Processor on worker (handles changes asynchronously)"); ChangeFeedProcessor changeFeedProcessorInstance = new ChangeFeedProcessorBuilder() .hostName("SampleHost_1") .feedContainer(feedContainer) .leaseContainer(leaseContainer) .handleChanges(handleChanges()) .options(options) .buildChangeFeedProcessor(); changeFeedProcessorInstance.start() .subscribeOn(Schedulers.boundedElastic()) .subscribe(); ``` -------------------------------- ### Error: Failed to start MCP server Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/troubleshooting Error message when the MCP server fails to start. Possible causes include port already in use, invalid settings, Cosmos DB Shell not properly installed, or firewall blocking the port. ```text Failed to start MCP server ``` -------------------------------- ### JSON output showing migration in progress Source: https://learn.microsoft.com/en-us/azure/cosmos-db/migrate-continuous-backup Example output after migration starts, showing migrationState with status InProgress and targetType Continuous. ```json { ... "backupPolicy": { ... "migrationState": { "status": "InProgress", "targetType": "Continuous" }, "type": "Periodic" }, ... } ``` -------------------------------- ### Initialize project template with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-go Initializes the quickstart project using the `cosmos-db-nosql-go-quickstart` template. You will be prompted to configure a unique environment name during initialization. ```Azure CLI azd init --template cosmos-db-nosql-go-quickstart ``` -------------------------------- ### Establish connection in Phoenix Source: https://learn.microsoft.com/en-us/azure/cosmos-db/migrate-hbase Uses JDBC to get a connection to an HBase cluster via Phoenix. This is the Phoenix alternative to the HBase connection example. ```Java //Use JDBC to get a connection to an HBase cluster Connection conn = DriverManager.getConnection("jdbc:phoenix:server1,server2:3333",props); ``` -------------------------------- ### Get a table (JavaScript) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-nodejs Creates an instance of the TableClient type using the GetTableClient function of the TableServiceClient type. The example uses a credential variable that must be defined. ```JavaScript let table = new TableClient("", "", credential); ``` -------------------------------- ### Initialize project with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-java Use this command to initialize the project from the cosmos-db-table-java-quickstart template. ```bash azd init --template cosmos-db-table-java-quickstart ``` -------------------------------- ### Install the kit with APM Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/agent-kit/setup Alternative installation command for agents that support APM. ```bash apm install AzureCosmosDB/cosmosdb-agent-kit ``` -------------------------------- ### help examples: general, specific command, container commands Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of using help: general help, help for a specific command (query), and help for container commands (mkcon). ```bash # General help CS > help # Help for specific command CS > help query # Help for container commands CS > help mkcon ``` -------------------------------- ### Get a table (TypeScript) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-nodejs Creates an instance of the TableClient type using the GetTableClient function of the TableServiceClient type. The example uses a credential variable that must be defined. ```TypeScript let table: TableClient = new TableClient("", "", credential); ``` -------------------------------- ### endpoint - Show endpoint example Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Example output of the endpoint command showing the account endpoint URL. ```bash CS > endpoint https://myaccount.documents.azure.com:443/ ``` -------------------------------- ### PowerShell: Sample Request for Table Backup Information Source: https://learn.microsoft.com/en-us/azure/cosmos-db/get-latest-restore-timestamp Example command to get backup information for a specific Table API table. Replace the sample values with your own. ```powershell Get-AzCosmosDBTableBackupInformation ` -ResourceGroupName "rg" ` -AccountName "amisitablepitracc1" ` -Name "table1" ` -Location "eastus" ``` -------------------------------- ### Compile and run the sample with npm run start Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-typescript Compiles and runs the sample. The package script loads the .env file automatically. The sample demonstrates control plane and data plane operations, including creating vector-indexed containers, loading data, and running vector searches. ```console npm run start ``` -------------------------------- ### Get-CosmosDbEmulatorStatus Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-windows-arguments Gets the status of the Azure Cosmos DB emulator. Returns a ServiceControllerStatus value indicating whether the emulator is starting, running, or stopped. If an error is encountered, no value is returned. ```APIDOC ## Get-CosmosDbEmulatorStatus ### Description Gets the status of the Azure Cosmos DB emulator. Returns one of the following `ServiceControllerStatus` values: `StartPending`, `Running`, or `Stopped`. If an error is encountered, no value is returned. ### Syntax ```powershell Get-CosmosDbEmulatorStatus [[-AlternativeInstallLocation] ] [] ``` ### Parameters #### Optional Parameters - **AlternativeInstallLocation** (String) - Optional - Specifies the installation location of the emulator if it is not installed in the default location. ### Examples #### Example 1: Get the status of an emulator installed in a custom folder ```powershell @parameters = { AlternativeInstallLocation = "D:\SomeFolder\AzureCosmosDBEmulator" } Get-CosmosDbEmulatorStatus @parameters ``` ### Return Value Returns one of the following `ServiceControllerStatus` values: - `ServiceControllerStatus.StartPending` - `ServiceControllerStatus.Running` - `ServiceControllerStatus.Stopped` If an error is encountered, no value is returned. ``` -------------------------------- ### Filter blob_list with SQL WHERE clause Source: https://learn.microsoft.com/en-us/azure/cosmos-db/postgresql/howto-ingest-azure-blob-storage Filters the blob_list output using a regular SQL WHERE clause on the path column. This example returns blobs whose path starts with 'e'. ```sql SELECT * FROM azure_storage.blob_list('pgquickstart','github') WHERE path LIKE 'e%'; ``` ```output -[ RECORD 1 ]----+--------------------------------- path | events.csv.gz bytes | 41691786 last_modified | 2022-10-12 18:49:51+00 etag | 0x8DAAC828B970928 content_type | application/x-gzip content_encoding | content_hash | 473b6ad25b7c88ff6e0a628889466aed ``` -------------------------------- ### Install PIP on Windows Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/support Runs the downloaded get-pip.py script to install PIP on Windows. This step follows the download of get-pip.py. ```bash python get-pip.py ``` -------------------------------- ### Run emulator with sample data Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-linux Starts the emulator container with ENABLE_INIT_DATA=true to load the included sample seed scripts from /scripts/init_examples/. ```bash docker run --name emulator --rm -e ENABLE_INIT_DATA=true -p 8081:8081 mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:vnext-latest ``` -------------------------------- ### Bicep template with Periodic backup policy Source: https://learn.microsoft.com/en-us/azure/cosmos-db/migrate-continuous-backup Example Bicep template showing a 'Periodic' backup policy with a 4-hour backup interval and 48-hour retention. This is the starting point for migration. ```bicep resource azureCosmosDBAccount 'Microsoft.DocumentDB/databaseAccounts@2025-04-15' = { name: '' properties: { // Other required properties omitted for brevity backupPolicy: { type: 'Periodic' periodicModeProperties: { backupIntervalInMinutes: 240 // 4 hours backupRetentionIntervalInHours: 48 // 2 days } } } } ``` -------------------------------- ### Start Kafka console producer to write to the hotels topic Source: https://learn.microsoft.com/en-us/azure/cosmos-db/kafka-connector-sink These PowerShell commands start the Kafka console producer to write records to the 'hotels' topic. Three options are provided: using Codespaces, using this repo's Confluent Platform setup (exec into broker container), or using your own Confluent Platform CLI. ```powershell # Option 1: If using Codespaces, use the built-in CLI utility kafka-console-producer --broker-list localhost:9092 --topic hotels # Option 2: Using this repo's Confluent Platform setup, first exec into the broker container docker exec -it broker /bin/bash kafka-console-producer --broker-list localhost:9092 --topic hotels # Option 3: Using your Confluent Platform setup and CLI install /bin/kafka-console-producer --broker-list --topic hotels ``` -------------------------------- ### Initialize Node.js project Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/langchain-javascript-get-started Creates a new directory, navigates into it, and initializes a Node.js project with npm. ```bash mkdir langchain-cosmosdb cd langchain-cosmosdb npm init -y ``` -------------------------------- ### Obtain responseIterator in LatestVersion mode from Beginning Source: https://learn.microsoft.com/en-us/azure/cosmos-db/change-feed-pull-model Gets a change feed iterator for the entire container in the default LatestVersion mode, starting from the beginning. The mode parameter is omitted because LatestVersion is the default. ```Python responseIterator = container.query_items_change_feed(start_time="Beginning") ``` -------------------------------- ### Run the quickstart script (Bash) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/integrated-embeddings Run the integrated_embeddings_quickstart.js script using Node.js. This command executes the script that creates the container and generates embeddings. ```Bash node integrated_embeddings_quickstart.js ``` -------------------------------- ### Initialize project with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-nodejs Initialize the project using the Azure Developer CLI template `cosmos-db-table-nodejs-quickstart`. ```bash azd init --template cosmos-db-table-nodejs-quickstart ``` -------------------------------- ### Get emulator certificate with openssl Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-linux Retrieves the emulator's TLS certificate using openssl and saves it to a temporary file. Replace localhost with the actual IP if the emulator was started with /AllowNetworkAccess. ```bash # If the emulator was started with /AllowNetworkAccess, replace localhost with the actual IP address of it: EMULATOR_HOST=localhost EMULATOR_PORT=8081 EMULATOR_CERT_PATH=/tmp/cosmos_emulator.cert openssl s_client -connect ${EMULATOR_HOST}:${EMULATOR_PORT} $EMULATOR_CERT_PATH ``` -------------------------------- ### ls - List examples Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Examples of listing databases, containers with details (-l), and human-readable sizes (-h). ```bash # List databases CS > ls # List containers with details CS > ls -l # List containers in human-readable format CS > ls -h ``` -------------------------------- ### Trigger completions with a partial query Source: https://learn.microsoft.com/en-us/azure/cosmos-db/vscode-extension/intellisense-auto-completion-preview Start typing a query in the query editor to trigger completion suggestions. The example shows a partial SELECT query with placeholders for field names and WHERE conditions. ```SQL SELECT c. FROM c WHERE c. ``` -------------------------------- ### pwd - Print working directory example Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Example output of the pwd command showing the current path. ```bash CS > pwd /mydb/users ``` -------------------------------- ### Build the sample with Maven Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gremlin/bulk-executor-dotnet Builds the sample application using Maven. This command packages the project into a JAR file with dependencies. ```bash mvn clean package ``` -------------------------------- ### Filter blob_list with prefix parameter Source: https://learn.microsoft.com/en-us/azure/cosmos-db/postgresql/howto-ingest-azure-blob-storage Uses the prefix parameter of blob_list to filter rows on the Azure Blob Storage side. This example returns blobs whose path starts with 'e'. ```sql SELECT * FROM azure_storage.blob_list('pgquickstart','github','e'); ``` ```output -[ RECORD 1 ]----+--------------------------------- path | events.csv.gz bytes | 41691786 last_modified | 2022-10-12 18:49:51+00 etag | 0x8DAAC828B970928 content_type | application/x-gzip content_encoding | content_hash | 473b6ad25b7c88ff6e0a628889466aed ``` -------------------------------- ### Install cassandra-driver for Node.js Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/quickstart-nodejs Installs the Cassandra client library from npm. Required for connecting to the Cosmos DB Cassandra account. ```bash npm install --save cassandra-driver ``` -------------------------------- ### Start-CosmosDbEmulator syntax Source: https://learn.microsoft.com/en-us/azure/cosmos-db/emulator-windows-arguments Shows the syntax for the Start-CosmosDbEmulator cmdlet, which starts the emulator. It includes parameters for network access, ports, consistency, data path, and enabling various APIs. ```powershell Start-CosmosDbEmulator [-AllowNetworkAccess] [-AlternativeInstallLocation ] [-CassandraPort ] [-ComputePort ] [-Consistency ] [-Credential ] [-DataPath ] [-DefaultPartitionCount ] [-DirectPort ] [-EnableMongoDb] [-EnableCassandra] [-EnableGremlin] [-EnableTable] [-EnableSqlCompute] [-EnablePreview] [-FailOnSslCertificateNameMismatch] [-GremlinPort ] [-TablePort ] [-SqlComputePort ] [-Key ] [-MongoPort ] [-MongoApiVersion ] [-NoFirewall] [-NoTelemetry] [-NoUI] [-NoWait] [-PartitionCount ] [-Port ] [-SimulateRateLimiting] [-Timeout ] [-Trace] [] ``` -------------------------------- ### Index progress output at 0% complete Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/indexing Example output document for an index operation that just started on a 'foo' collection and 'bar' database, showing 0% progress until it reaches a measurable level. ```json { "inprog": [ { ... "command": { "createIndexes": foo "indexes": [], "$db": bar }, "msg": "Index Build (background) Index Build (background): 0 %", "progress": { "done": 0, "total": 100 }, ... } ], "ok": 1 } ``` -------------------------------- ### Example output (text) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/integrated-embeddings Example output showing inserted items and generated embeddings with dimensions and preview. ```text Inserted item: item-1 Inserted item: item-2 Inserted item: item-3 Waiting for embeddings: ['item-1', 'item-2', 'item-3'] Generated embedding for item-1 (dimensions: 1536, preview: [0.0123, -0.0456, 0.0789]...) Generated embedding for item-2 (dimensions: 1536, preview: [-0.0231, 0.0567, 0.0103]...) Generated embedding for item-3 (dimensions: 1536, preview: [0.0456, -0.0210, 0.0398]...) ``` -------------------------------- ### Create a new project directory Source: https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-javascript-get-started Creates a new directory named cosmos-db-nosql-javascript-samples and changes into it. This is the first step in setting up your local project. ```bash mkdir cosmos-db-nosql-javascript-samples && cd ./cosmos-db-nosql-javascript-samples ``` -------------------------------- ### Example output for full-text query status check Source: https://learn.microsoft.com/en-us/azure/cosmos-db/monitor-resource-logs This JSON output is the expected response from the GET request that checks the full-text query status. It shows the account name and the enableFullTextQuery value as True. ```json { "accountName": "", "fullTextQueryEnabled": "True" } ``` -------------------------------- ### Change directory and build the app Source: https://learn.microsoft.com/en-us/azure/cosmos-db/tutorial-dotnet-bulk-import Navigate into the created project folder and build the application. The build output is shown in the next snippet. ```bash cd bulk-import-demo dotnet build ``` -------------------------------- ### PowerShell script to start Azure Cosmos DB emulator Source: https://learn.microsoft.com/en-us/azure/cosmos-db/tutorial-setup-ci-cd This PowerShell script imports the Azure Cosmos DB emulator module, starts the emulator with the Start-CosmosDbEmulator cmdlet using -NoFirewall and -NoUI flags, and outputs an object containing emulator details and endpoints. It is intended to be run on a windows-2019 agent or a self-hosted Windows agent with the emulator installed. ```powershell # Write your PowerShell commands here. dir "$env:ProgramFiles\Azure Cosmos DB Emulator\" Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator" $startEmulatorCmd = "Start-CosmosDbEmulator -NoFirewall -NoUI" Write-Host $startEmulatorCmd Invoke-Expression -Command $startEmulatorCmd # Pipe an emulator info object to the output stream $Emulator = Get-Item "$env:ProgramFiles\Azure Cosmos DB Emulator\Microsoft.Azure.Cosmos.Emulator.exe" $IPAddress = Get-NetIPAddress -AddressFamily IPV4 -AddressState Preferred -PrefixOrigin Manual | Select-Object IPAddress New-Object PSObject @{ Emulator = $Emulator.BaseName Version = $Emulator.VersionInfo.ProductVersion Endpoint = @($(hostname), $IPAddress.IPAddress) | ForEach-Object { "https://${_}:8081/" } MongoDBEndpoint = @($(hostname), $IPAddress.IPAddress) | ForEach-Object { "mongodb://${_}:10255/" } CassandraEndpoint = @($(hostname), $IPAddress.IPAddress) | ForEach-Object { "tcp://${_}:10350/" } GremlinEndpoint = @($(hostname), $IPAddress.IPAddress) | ForEach-Object { "http://${_}:8901/" } TableEndpoint = @($(hostname), $IPAddress.IPAddress) | ForEach-Object { "https://${_}:8902/" } IPAddress = $IPAddress.IPAddress } ``` -------------------------------- ### RU/s calculation example for quantizedFlat workload Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/vector-search-performance-tips Applies the RU sizing formula to a workload of 100 vector searches/sec and 50 inserts/sec with a quantizedFlat index. Provides a starting point for choosing an autoscale ceiling. ```text = (100 × 45) + (50 × 36) + 10 % buffer = 4,500 + 1,800 + 630 = 6,930 RU/s → provision ~7,000 RU/s using Autoscale. ``` -------------------------------- ### Clone the bulk executor .NET sample repository Source: https://learn.microsoft.com/en-us/azure/cosmos-db/bulk-executor-dotnet Clones the Azure Cosmos DB bulk executor .NET getting started repository from GitHub. Run this command in a command prompt after navigating to the desired directory. ```bash git clone https://github.com/Azure/azure-cosmosdb-bulkexecutor-dotnet-getting-started.git ``` -------------------------------- ### Initialize project with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-python Initialize the project from the cosmos-db-table-python-quickstart template. During initialization, configure a unique environment name. ```bash azd init --template cosmos-db-table-python-quickstart ``` -------------------------------- ### PowerShell workaround for az cosmosdb update capabilities Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/how-to-configure-capabilities If you are using PowerShell and get an error with the standard `--capabilities` syntax, use a PowerShell array to list the capabilities. This example keeps `EnableMongo` and removes `DisableRateLimitingResponses`. ```bash az cosmosdb update \ --resource-group \ --name \ --capabilities @("EnableMongo") ``` -------------------------------- ### Initialize project with azd init Source: https://learn.microsoft.com/en-us/azure/cosmos-db/table/quickstart-go Use `azd init` with the template `cosmos-db-table-go-quickstart` to initialize the project. During initialization, configure a unique environment name. ```bash azd init --template cosmos-db-table-go-quickstart ``` -------------------------------- ### Start the dual-write proxy (basic) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/migrate-data-dual-write-proxy Starts the proxy on a node, connecting to the local source and a target server. Requires that source and target endpoints have the same username/password and implement SSL. ```bash java -jar target/cassandra-proxy-1.0-SNAPSHOT-fat.jar localhost --proxy-jks-file --proxy-jks-password ``` -------------------------------- ### PowerShell: Sample Request for Gremlin Graph Backup Information Source: https://learn.microsoft.com/en-us/azure/cosmos-db/get-latest-restore-timestamp Example command to get backup information for a specific Gremlin graph. Replace the sample values with your own resource group, account, database, graph, and location. ```powershell Get-AzCosmosDBGremlinGraphBackupInformation ` -ResourceGroupName "rg" ` -AccountName "amisigremlinpitracc1" ` -GremlinDatabaseName "db1" ` -Name "graph1" ` -Location "eastus" ``` -------------------------------- ### Specify source and target ports Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/migrate-data-dual-write-proxy Starts the proxy with explicit source and target ports using --source-port and --target-port. The default ports are 9042; this example uses 9042 for source and 10350 for target. ```bash java -jar target/cassandra-proxy-1.0-SNAPSHOT-fat.jar localhost \ --source-port 9042 --target-port 10350 --proxy-jks-file \ --proxy-jks-password --target-username --target-password ``` -------------------------------- ### Run the sample Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-python Run the Python sample that creates vector indexes, loads data, and runs vector queries. ```console python -m src.index ``` -------------------------------- ### Create connect_friends.js script for multi-document transaction Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/use-multi-document-transactions JavaScript script that inserts data into the friends collection, starts a transaction, performs updates, aborts on error, and commits. This example does not work in MongoSH beta embedded in MongoDB Compass. ```javascript // insert data into friends collection db.getMongo().getDB("users").friends.insert({name:"Tom"}) db.getMongo().getDB("users").friends.insert({name:"Mike"}) // start transaction var session = db.getMongo().startSession(); var friendsCollection = session.getDatabase("users").friends; session.startTransaction(); // operations in transaction try { friendsCollection.updateOne({ name: "Tom" }, { $set: { friendOf: "Mike" } } ); friendsCollection.updateOne({ name: "Mike" }, { $set: { friendOf: "Tom" } } ); } catch (error) { // abort transaction on error session.abortTransaction(); throw error; } // commit transaction session.commitTransaction(); ``` -------------------------------- ### Create a container with partition key and manual throughput (C#) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-create-container Creates a database and a container with a partition key and 400 RU/s manual throughput. Uses the previously created CosmosClient. The container ID and partition key path are specified in the properties. ```csharp // Create a container with a partition key and provision 400 RU/s manual throughput. Database database = await client.CreateDatabaseIfNotExistsAsync(databaseId); ContainerProperties containerProperties = new ContainerProperties() { Id = containerId, PartitionKeyPath = "/myPartitionKey" }; var throughput = ThroughputProperties.CreateManualThroughput(400); Container container = await database.CreateContainerIfNotExistsAsync(containerProperties, throughput); ``` -------------------------------- ### Configure Cluster with Load-Balancing Policy (Java DataStax v3.x) Source: https://learn.microsoft.com/en-us/azure/cosmos-db/cassandra/troubleshoot-common-issues Example of building a Cassandra cluster with a load-balancing policy using DCAwareRoundRobinPolicy. If the withLocalDc() value doesn't match the contact point datacenter, you may get NoHostAvailableException. ```java cluster = Cluster.builder() .addContactPoint(cassandraHost) .withPort(cassandraPort) .withCredentials(cassandraUsername, cassandraPassword) .withPoolingOptions(new PoolingOptions() .setConnectionsPerHost(HostDistance.LOCAL, 1, 2) .setMaxRequestsPerConnection(HostDistance.LOCAL, 32000).setMaxQueueSize(Integer.MAX_VALUE)) .withSSL(sslOptions) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("West US").build()) .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM)) .withSocketOptions(getSocketOptions()) .build(); ``` -------------------------------- ### GitHub Actions workflow for Python unit tests with Azure Cosmos DB emulator Source: https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-develop-emulator Defines a CI workflow that starts the Azure Cosmos DB emulator, installs pytest, and runs the Python test suite on a windows-latest runner. ```yaml name: Continuous Integration on: push: branches: - main jobs: unit_tests: name: Run Python unit tests runs-on: windows-latest steps: - name: Checkout (GitHub) uses: actions/checkout@v3 - name: Start Azure Cosmos DB emulator run: | Write-Host "Launching Cosmos DB Emulator" Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator" Start-CosmosDbEmulator - name: Install test runner run: pip install pytest - name: Run Python tests run: pytest ``` -------------------------------- ### Sample application output Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/readpreference-global-distribution After updating the connection string and read region, the sample application runs and produces this output, showing successful queries from different read preferences. ```text connected! readDefaultfunc query completed! readFromNearestfunc query completed! readFromRegionfunc query completed! readDefaultfunc query completed! readFromNearestfunc query completed! readFromRegionfunc query completed! readDefaultfunc query completed! readFromSecondaryfunc query completed! ``` -------------------------------- ### Get all indexes in collection using indexes() Source: https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/how-to-javascript-manage-collections Retrieves all indexes in the 'products' collection of the 'adventureworks' database. The method returns an object whose keys are index positions and values are index definitions. The example logs each index with its key and value. ```JavaScript // Get all indexes in collection const collectionInstance = await client .db('adventureworks') .collection('products'); const indexes = await collectionInstance.indexes(); console.log( `Indexes on collection:\n${Object.keys(indexes).map(key => `\t${key}: ${JSON.stringify(indexes[key])}\n`)}` ); ``` -------------------------------- ### Create get-started.js with imports and Azure OpenAI config Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gen-ai/langchain-javascript-get-started Imports required LangChain packages and configures Azure OpenAI using environment variables. ```javascript import { AzureCosmosDBNoSQLVectorStore, AzureCosmosDBNoSQLSearchType } from "@langchain/azure-cosmosdb"; import { AzureChatOpenAI, AzureOpenAIEmbeddings } from "@langchain/openai"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { StringOutputParser } from "@langchain/core/output_parsers"; import { RunnableSequence } from "@langchain/core/runnables"; import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters"; import { Document } from "@langchain/core/documents"; import { readFileSync } from "fs"; // Azure OpenAI configuration (reads from environment variables) const azureOpenAIConfig = { azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, }; ``` -------------------------------- ### Bootstrap Next.js app with with-azure-cosmos example Source: https://learn.microsoft.com/en-us/azure/cosmos-db/vercel-integration Run one of these commands to create a new Next.js app using the with-azure-cosmos example. Choose npm, yarn, or pnpm based on your package manager. ```bash npx create-next-app --example with-azure-cosmos with-azure-cosmos-app yarn create next-app --example with-azure-cosmos with-azure-cosmos-app pnpm create next-app --example with-azure-cosmos with-azure-cosmos-app ``` -------------------------------- ### C#: Discover read/write locations and construct regional Gremlin endpoints Source: https://learn.microsoft.com/en-us/azure/cosmos-db/gremlin/use-regional-endpoints Use the Azure Cosmos DB .NET SDK to get the database account and retrieve writable and readable locations. The example shows how to convert a preferred read location to the form '[accountname]-[region].gremlin.cosmos.azure.com' by replacing the document endpoint. Note that the API to get readLocations and writeLocations may vary depending on the SDK version and language. ```csharp // Depending on the version and the language of the SDK (.NET vs Java vs Python) // the API to get readLocations and writeLocations may vary. IDocumentClient documentClient = new DocumentClient( new Uri(cosmosUrl), cosmosPrimaryKey, connectionPolicy, consistencyLevel); DatabaseAccount databaseAccount = await cosmosClient.GetDatabaseAccountAsync(); IEnumerable writeLocations = databaseAccount.WritableLocations; IEnumerable readLocations = databaseAccount.ReadableLocations; // Pick write or read locations to construct regional endpoints for. foreach (string location in readLocations) { // Convert preferred read location to the form "[acountname]-[region].gremlin.cosmos.azure.com". string regionalGremlinEndPoint = location .Replace("http:\/\/", string.Empty) .Replace("documents.azure.com:443/", "gremlin.cosmos.azure.com"); // Use code from the previous sample to instantiate Gremlin client. } ``` -------------------------------- ### GitHub Actions workflow for Node.js unit tests with Azure Cosmos DB emulator Source: https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-develop-emulator Defines a CI workflow that starts the Azure Cosmos DB emulator, installs mocha globally, and runs the Node.js test suite on a windows-latest runner. ```yaml name: Continuous Integration on: push: branches: - main jobs: unit_tests: name: Run Node.js unit tests runs-on: windows-latest steps: - name: Checkout (GitHub) uses: actions/checkout@v3 - name: Start Azure Cosmos DB emulator run: | Write-Host "Launching Cosmos DB Emulator" Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator" Start-CosmosDbEmulator - name: Install test runner run: npm install --global mocha - name: Run Node.js tests run: mocha ``` -------------------------------- ### CLI startup options syntax Source: https://learn.microsoft.com/en-us/azure/cosmos-db/shell/command-reference Syntax for launching the shell with connect options as CLI startup arguments, using the --connect- prefix. ```bash cosmosdbshell --connect [--connect-tenant=] [--connect-managed-identity=] [--connect-subscription=] [--connect-resource-group=] ``` -------------------------------- ### Change to the Go sample directory Source: https://learn.microsoft.com/en-us/azure/cosmos-db/quickstart-create-vector-index-go Change to the Go sample directory 'nosql-create-index-go'. ```bash cd nosql-create-index-go ```