Quickstart: Full-text search in Azure Cosmos DB

In this quickstart, you configure a text property for full-text search and run a BM25-ranked query in Azure Cosmos DB.

Choose the experience that best fits your workflow:

Experience Best for
Azure portal A browser-based setup with no local tools
Visual Studio Code A reproducible setup for developers and coding agents

Both paths include instructions to create the same full-text-search-quickstart database and items container before running the sample. Choose one path. The sample inserts one item and runs a ranked query against /description.

Important

For both paths, first complete Set up an account, Configure access, and Get endpoint. Then follow either the Azure portal or Visual Studio Code instructions.

Prerequisites

  • An Azure subscription. If you don't have one, create a free account.
  • Access to an Azure Cosmos DB account with provisioned throughput, with or without the free-tier discount, or permission to create one as described in Set up an account.
  • Network access from the environment where you run the quickstart to your Azure Cosmos DB account.
  • Permission to create databases and containers through the Azure management plane, and data access as described in Configure access.

For the Visual Studio Code path, you also need:

Set up an account

For either path, use an Azure Cosmos DB account with provisioned throughput. Free tier is optional. Create or choose the account manually.

  1. Sign in to the Azure portal.
  2. If you already have an Azure Cosmos DB account with provisioned throughput, open it. Otherwise, follow Create an Azure Cosmos DB account. If the free-tier discount is available, set Apply Free Tier Discount to Apply when you create the account.

Your subscription can have only one Azure Cosmos DB free-tier account, and free tier must be enabled when you create the account. If the discount isn't available, use an existing Azure Cosmos DB account with provisioned throughput or create one without the discount. You don't need to switch subscriptions.

The setup uses a container with 400 RU/s of manual throughput. Without the free-tier discount, standard throughput and storage charges apply. With free tier, the first 1,000 RU/s and 25 GB of storage across the account are covered. Other workloads consume the same allowance, so check your account's total usage to avoid charges.

Configure access

This quickstart uses Microsoft Entra ID authentication and Azure Cosmos DB native data-plane role-based access control. It doesn't use account keys and works when key-based authentication is disabled.

  1. Follow Grant data-plane access to assign Cosmos DB Built-in Data Contributor to your user identity on the account. This role allows the sample to insert and query items; you don't need a separate reader role.
  2. Use that same identity when you sign in to Cloud Shell or the Azure CLI.

The person assigning the role needs Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments/write permission on the account. If you don't have this permission, ask your account administrator to assign the role. Azure subscription Contributor access alone doesn't grant data access.

Database and container creation use the management plane and require separate permissions, such as those provided by DocumentDB Account Contributor. The Python sample only inserts and queries items.

Note

Role assignments can take a few minutes to propagate. If a data request returns a permission error immediately after assignment, wait and retry.

Get endpoint

Your account endpoint is the value labeled URI on your Azure Cosmos DB account's Keys page. It identifies the account that the sample connects to and doesn't contain an account key. Copy the URI, not a key or connection string.

  1. Open your Azure Cosmos DB account in the Azure portal.
  2. In the account menu, select Keys, and copy the URI, which looks like https://<account-name>.documents.azure.com:443/.
  3. Take note of this value to use later as AZURE_COSMOS_ENDPOINT.

Azure portal

Use Cloud Shell to create the database and container, then insert and query an item without installing tools locally. Complete the account and access setup first.

Create the database and container

Use the Azure CLI management commands to create the full-text policy and index before running the Python sample.

  1. Open Cloud Shell in the Azure portal, and choose Bash if prompted.

  2. Select the subscription that contains your account:

    az account set --subscription "<subscription-id>"
    
  3. Replace the RESOURCE_GROUP and ACCOUNT_NAME placeholders at the top with your actual resource group and account name, and run the following block. It creates a database and a container with /category as the partition key and /description as the full-text search path.

    bash <<'SETUP'
    set -euo pipefail
    
    RESOURCE_GROUP="<resource-group-name>"
    ACCOUNT_NAME="<account-name>"
    
    az cosmosdb sql database create \
        --resource-group "$RESOURCE_GROUP" \
        --account-name "$ACCOUNT_NAME" \
        --name full-text-search-quickstart \
        --output none
    
    az cosmosdb sql container create \
        --resource-group "$RESOURCE_GROUP" \
        --account-name "$ACCOUNT_NAME" \
        --database-name full-text-search-quickstart \
        --name items \
        --partition-key-path /category \
        --throughput 400 \
        --full-text-policy '{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"}]}' \
        --idx '{"indexingMode":"consistent","automatic":true,"includedPaths":[{"path":"/*"}],"excludedPaths":[{"path":"/\"_etag\"/?"}],"fullTextIndexes":[{"path":"/description"}]}' \
        --output none
    SETUP
    

Continue only after both commands succeed. If you already have a container with these names, verify that it has both the full-text policy and index for /description before running the sample.

Sign in and set the endpoint

The Python sample uses AzureCliCredential to request an Azure Cosmos DB data-plane token through Azure CLI. Creating resources with Azure CLI doesn't verify that this token is available.

  1. In the same Bash Cloud Shell session where you run the sample, sign in with the identity that has Cosmos DB Built-in Data Contributor access. Follow the device-code sign-in instructions, and then select the subscription that contains your account.

    az login --use-device-code
    az account set --subscription "<subscription-id>"
    
  2. Set AZURE_COSMOS_ENDPOINT to the URI you copied in Get endpoint:

    export AZURE_COSMOS_ENDPOINT="<insert endpoint here>"
    

If the sample reports AzureCliCredential.get_token_info failed: Please run 'az login' to set up an account, repeat the sign-in step in the same shell and rerun the sample. This error occurs during token acquisition, before the sample can insert or query items. If sign-in fails, resolve the Azure CLI authentication error before continuing.

Run the quickstart

Paste the following block into Cloud Shell. It uses your Cloud Shell Azure CLI identity and runs in a separate Bash process so an error doesn't close your shell.

bash <<'QUICKSTART'
set -euo pipefail

: "${AZURE_COSMOS_ENDPOINT:?Set the account endpoint before running this block.}"

python -m pip install --user --quiet azure-cosmos azure-identity

python - <<'PY'
import os

from azure.cosmos import CosmosClient
from azure.identity import AzureCliCredential


item = {
    "id": "fts-quickstart-1",
    "category": "quickstart",
    "description": "A rugged mountain bike for steep climbs and rocky trails.",
}
query = """
SELECT TOP 10
    c.id,
    c.description
FROM c
WHERE FullTextContainsAny(c.description, "bike", "trail")
ORDER BY RANK FullTextScore(c.description, "bike", "trail")
"""

with AzureCliCredential() as credential:
    with CosmosClient(os.environ["AZURE_COSMOS_ENDPOINT"], credential=credential) as client:
        container = client.get_database_client(
            "full-text-search-quickstart"
        ).get_container_client("items")
        container.upsert_item(item)
        print(f"Inserted verification item: {item['id']}")

        print("Full-text search results:")
        for result in container.query_items(
            query=query,
            enable_cross_partition_query=True,
        ):
            print(f"- {result['id']}: {result['description']}")
PY

QUICKSTART

Review the output.

Inserted verification item: fts-quickstart-1
Full-text search results:
- fts-quickstart-1: A rugged mountain bike for steep climbs and rocky trails.

FullTextContainsAny filters for items that contain bike or trail, and FullTextScore ranks the matches by BM25 relevance.

Visual Studio Code

Use this path to create the database and container from the Visual Studio Code terminal, and then insert and query an item with the Azure Cosmos DB Python SDK. Complete the account and access setup first. You don't need to complete the Azure portal path.

Set up the project

  1. Create a project folder and open it in Visual Studio Code.

    mkdir cosmos-full-text-search-quickstart
    cd cosmos-full-text-search-quickstart
    code .
    
  2. In the Visual Studio Code terminal, create and activate a virtual environment.

    python -m venv .venv
    .\.venv\Scripts\Activate.ps1
    

  1. Install the Azure Cosmos DB and Azure Identity packages.

    python -m pip install azure-cosmos azure-identity
    

Sign in and set the endpoint

  1. In the Visual Studio Code terminal, sign in with the identity that has Cosmos DB Built-in Data Contributor access. Select the subscription that contains your account.

    az login
    az account set --subscription "<subscription-id>"
    
  2. Set AZURE_COSMOS_ENDPOINT to the URI you copied in Get endpoint.

    $env:AZURE_COSMOS_ENDPOINT = "https://<account-name>.documents.azure.com:443/"
    

Create the database and container

In the Visual Studio Code terminal, use the Azure CLI management commands to create a database and a container with /category as the partition key, a full-text policy for /description, and a matching full-text index. These commands use the identity and subscription you selected in the previous step and require management-plane permissions as described in Configure access.

Replace the resource group and account name placeholders, and then run the block for your terminal.

Use JSON files for the policies to avoid differences in how PowerShell versions pass JSON arguments to Azure CLI. This block creates full-text-policy.json and indexing-policy.json in your project folder.

$resourceGroup = "<resource-group-name>"
$accountName = "<account-name>"

@'
{"defaultLanguage":"en-US","fullTextPaths":[{"path":"/description","language":"en-US"}]}
'@ | Set-Content -Path full-text-policy.json -Encoding ascii

@'
{"indexingMode":"consistent","automatic":true,"includedPaths":[{"path":"/*"}],"excludedPaths":[{"path":"/\"_etag\"/?"}],"fullTextIndexes":[{"path":"/description"}]}
'@ | Set-Content -Path indexing-policy.json -Encoding ascii

az cosmosdb sql database create `
    --resource-group "$resourceGroup" `
    --account-name "$accountName" `
    --name full-text-search-quickstart `
    --output none

if ($LASTEXITCODE -ne 0) { throw "Database creation failed." }

az cosmosdb sql container create `
    --resource-group "$resourceGroup" `
    --account-name "$accountName" `
    --database-name full-text-search-quickstart `
    --name items `
    --partition-key-path /category `
    --throughput 400 `
    --full-text-policy '@full-text-policy.json' `
    --idx '@indexing-policy.json' `
    --output none

if ($LASTEXITCODE -ne 0) { throw "Container creation failed." }

Continue only after both commands succeed. If you already have a container with these names, verify that it has both the full-text policy and index for /description before running the sample. The Python sample doesn't create or configure these resources.

Create the app

Create a file named app.py and add the following code.

import os

from azure.cosmos import CosmosClient
from azure.identity import AzureCliCredential

verification_item = {
    "id": "fts-quickstart-1",
    "category": "quickstart",
    "description": "A rugged mountain bike for steep climbs and rocky trails.",
}

query = """
SELECT TOP 10
    c.id,
    c.description
FROM c
WHERE FullTextContainsAny(c.description, "bike", "trail")
ORDER BY RANK FullTextScore(c.description, "bike", "trail")
"""

with AzureCliCredential() as credential:
    with CosmosClient(os.environ["AZURE_COSMOS_ENDPOINT"], credential=credential) as client:
        container = client.get_database_client(
            "full-text-search-quickstart"
        ).get_container_client("items")
        container.upsert_item(verification_item)
        print(f"Inserted verification item: {verification_item['id']}")

        print("Full-text search results:")
        for result in container.query_items(
            query=query,
            enable_cross_partition_query=True,
        ):
            print(f"- {result['id']}: {result['description']}")

Run the app

  1. In the Visual Studio Code terminal, run the app.

    python app.py
    
  2. Review the output. The output should be similar to this example:

    Inserted verification item: fts-quickstart-1
    Full-text search results:
    - fts-quickstart-1: A rugged mountain bike for steep climbs and rocky trails.
    

The app uses upsert_item so you can run it more than once without creating duplicate items. The query spans partition key values, so enable_cross_partition_query is set to True.

If the container is missing or doesn't have the full-text policy and index for /description, return to Create the database and container. Rerunning the app doesn't create or configure containers.

Try other full-text queries

After the first query works, replace it with one of these examples.

Use FullTextContains when a word or phrase must appear:

SELECT TOP 10 *
FROM c
WHERE FullTextContains(c.description, "bike")

Use fuzzy search to allow spelling differences. The maximum edit distance is 2:

SELECT TOP 10 *
FROM c
WHERE FullTextContains(c.description, {"term": "byke", "distance": 2})

Use an aggregation to count matching items by category. For this query, also replace the result-printing line in the Python sample with print(f"- {result['facetKey']}: {result['facetCount']}").

SELECT
    c.category AS facetKey,
    COUNT(1) AS facetCount
FROM c
WHERE FullTextContains(c.description, "bike")
GROUP BY c.category

For more query patterns, including multi-language search and facets, see Full-text search in Azure Cosmos DB.

Clean up resources

Warning

Deleting the quickstart database permanently removes all its containers and items.

For either path, delete only the quickstart database. Keep your account and any other databases.

  1. In the Azure portal, open the account you used for this quickstart.
  2. Select Data Explorer.
  3. Locate the full-text-search-quickstart database, and select Delete Database.
  4. Confirm the database name and complete the deletion.