Use LlamaIndex with Azure DocumentDB

LlamaIndex is a data framework for building LLM applications over your own data. It chunks and embeds source documents, stores them in a vector store, and exposes retrievers and query engines that combine retrieval with an LLM call. The llama-index-vector-stores-azurecosmosmongo package provides AzureCosmosDBMongoDBVectorSearch, a VectorStore implementation that targets the MongoDB-compatible wire protocol exposed by Azure DocumentDB.

This how-to walks through wiring the integration to your cluster, ingesting documents into a VectorStoreIndex, creating a DiskANN vector index, and running semantic and metadata-filtered RAG queries.

What is LlamaIndex?

LlamaIndex provides a small set of building blocks for retrieval-augmented generation:

  • Document and Node — the source text and the chunked, embedded units written to a vector store.
  • VectorStoreIndex — orchestrates chunking, embedding, and persistence into a configured VectorStore.
  • Retrievers and query engines — pull the top-k most relevant nodes for a query (optionally with metadata filters) and combine retrieval with an LLM and a prompt template.

AzureCosmosDBMongoDBVectorSearch implements the VectorStore interface against Azure DocumentDB. Vector queries run as $search aggregations using the cosmosSearch operator, which Azure DocumentDB executes natively.

LlamaIndex Azure DocumentDB integration

Azure DocumentDB pairs well with LlamaIndex for the following reasons:

  • One store for source data and vectors. Native vector indexing lives alongside document data, enabling RAG and similarity search without introducing a separate vector store. Chunks, metadata, and embeddings stay in the same collection.
  • MongoDB-compatible drivers and integrations. Azure DocumentDB exposes the MongoDB wire protocol, so pymongo and the LlamaIndex Cosmos vCore vector store work against your cluster directly. MongoDB drivers and tools work without application-level rewrites, simplifying migration in common scenarios.
  • Pre-filter inside vector search. Pass the integration's pre_filter through vector_store_kwargs to include a cosmosSearch.filter clause in the vector search request. Version 0.9.0 doesn't translate LlamaIndex MetadataFilters into this clause.
  • DiskANN, HNSW, and IVF indexes. Pick the algorithm that matches your dataset size and recall/latency budget.

Get started: install dependencies

Install LlamaIndex, the Cosmos Mongo vCore vector store, Azure OpenAI embedding and LLM providers, file readers, and the MongoDB driver. Copy your Connection string value from the Azure portal for your DocumentDB cluster and store it as DOCUMENTDB_URI.

pip install llama-index \
    llama-index-vector-stores-azurecosmosmongo \
    llama-index-llms-azure-openai \
    llama-index-embeddings-azure-openai \
    llama-index-readers-file \
    docx2txt \
    pymongo

Note

The vector store integration is Python-only. If you're building a TypeScript app, use the mongodb driver and run vector queries with the $search + cosmosSearch aggregation pipeline shown in Vector search in Azure DocumentDB.

Configure Azure OpenAI for embeddings and chat

The example uses Azure OpenAI for both the embedding model and the chat completion model. Set the following environment variables before running the code:

Variable Purpose
AZURE_OPENAI_ENDPOINT The Azure OpenAI resource endpoint.
AZURE_OPENAI_API_KEY API key for the resource.
AZURE_OPENAI_API_VERSION API version (for example, 2024-08-01-preview).
AZURE_OPENAI_CHAT_DEPLOYMENT Deployment name for the chat model (for example, gpt-4o-mini).
AZURE_OPENAI_EMBEDDING_DEPLOYMENT Deployment name for the embedding model (for example, text-embedding-3-small).
import os

from llama_index.core import Settings
from llama_index.llms.azure_openai import AzureOpenAI
from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding

Settings.llm = AzureOpenAI(
    model="gpt-4o-mini",
    deployment_name=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_version=os.environ["AZURE_OPENAI_API_VERSION"],
    temperature=0,
)

Settings.embed_model = AzureOpenAIEmbedding(
    model="text-embedding-3-small",
    deployment_name=os.environ["AZURE_OPENAI_EMBEDDING_DEPLOYMENT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_version=os.environ["AZURE_OPENAI_API_VERSION"],
)

Settings.chunk_size = 256
Settings.chunk_overlap = 20

To use OpenAI (non-Azure) instead, swap AzureOpenAI/AzureOpenAIEmbedding for OpenAI/OpenAIEmbedding and provide OPENAI_API_KEY.

Load source documents

Use SimpleDirectoryReader to load any folder of .pdf, .txt, .md, or .docx files into a list of Document objects.

from llama_index.core import SimpleDirectoryReader

documents = SimpleDirectoryReader(input_dir="./data").load_data()
print(f"Loaded {len(documents)} documents.")

You can also build Document objects in code with custom metadata to enable filtered retrieval later:

from llama_index.core import Document

documents = [
    Document(
        text="Azure DocumentDB supports DiskANN, HNSW, and IVF vector indexes.",
        metadata={"title": "Vector indexes", "category": "vector-search"},
    ),
    Document(
        text="Reuse a single MongoClient instance per process for best throughput.",
        metadata={"title": "Connection best practices", "category": "ops"},
    ),
]

Connect to Azure DocumentDB and build the index

Wrap a pymongo.MongoClient with AzureCosmosDBMongoDBVectorSearch and a StorageContext, then call VectorStoreIndex.from_documents. The index chunks each document, embeds the chunks with Settings.embed_model, and writes them to the configured collection.

In llama-index-vector-stores-azurecosmosmongo version 0.9.0, the vector-store constructor issues a createIndexes command before you ingest documents. Set cosmos_search_kwargs explicitly to select DiskANN. Without a kind option, the integration defaults to HNSW, even if index_name contains diskann. Set dimensions to match your embedding model's output; this example uses the default 1,536 dimensions for text-embedding-3-small.

Use a new collection for this example. If llamaindex_db.documents already exists, set COLLECTION_NAME to a new name before running the following code. To reuse an existing collection, inspect its vector index before running the constructor again. Changing the constructor options doesn't convert an existing HNSW index to DiskANN. If the existing definition differs, use a new collection and index for the example, and preserve the original collection and its data.

import pymongo
from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.vector_stores.azurecosmosmongo import AzureCosmosDBMongoDBVectorSearch

DB_NAME = "llamaindex_db"
COLLECTION_NAME = "documents"
VECTOR_INDEX_NAME = "vector-diskann"
EMBEDDING_DIMS = 1536  # text-embedding-3-small default output dimensions

mongodb_client = pymongo.MongoClient(
    os.environ["DOCUMENTDB_URI"],
    appname="llamaindex-sample",
)

vector_store = AzureCosmosDBMongoDBVectorSearch(
    mongodb_client=mongodb_client,
    db_name=DB_NAME,
    collection_name=COLLECTION_NAME,
    index_name=VECTOR_INDEX_NAME,
    embedding_key="embedding",
    text_key="text",
    cosmos_search_kwargs={
        "kind": "vector-diskann",
        "dimensions": EMBEDDING_DIMS,
        "similarity": "COS",
        "maxDegree": 32,
        "lBuild": 50,
    },
)

storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_documents(
    documents,
    storage_context=storage_context,
    show_progress=True,
)

Key parameters:

Parameter Purpose
db_name / collection_name Target database and collection.
index_name Name assigned to the vector index when it's created; the name doesn't select the algorithm.
embedding_key Field that stores the vector.
text_key Field that stores the chunk text.
cosmos_search_kwargs Vector index options, including kind, dimensions, similarity, and algorithm-specific settings.

Inspect the DiskANN vector index

The constructor already requests index creation, so you don't need a separate create_index call. Inspect the stored definition rather than checking only the index name:

coll = mongodb_client[DB_NAME][COLLECTION_NAME]
for vector_index in coll.list_indexes():
    if vector_index["name"] == VECTOR_INDEX_NAME:
        print(vector_index)

Confirm that the index targets the embedding field and that its vector settings specify kind: vector-diskann, dimensions: 1536, and similarity: COS. A matching index name alone doesn't verify these settings.

To use HNSW or IVF in a new collection, set kind in cosmos_search_kwargs to vector-hnsw or vector-ivf and replace the DiskANN-specific options with the corresponding algorithm options (for example, m and efConstruction for HNSW, or numLists for IVF).

Query the index

Convert the index into a query engine and ask natural-language questions. The engine retrieves the top-k most similar chunks and grounds the LLM's answer in them.

import textwrap

query_engine = index.as_query_engine()

response = query_engine.query("Which vector index should I pick for production?")
print(textwrap.fill(str(response), 100))

To inspect the chunks the engine grounded its answer on, read response.source_nodes:

for src in response.source_nodes:
    print(f"- {src.metadata.get('title')} (score={src.score:.3f})")

Filter retrieval by metadata

In llama-index-vector-stores-azurecosmosmongo version 0.9.0, use the integration-specific pre_filter argument rather than LlamaIndex MetadataFilters. Pass it through the query engine's vector_store_kwargs so the retriever forwards it to the vector store. The integration includes this predicate in cosmosSearch.filter, not in a separate post-retrieval filter.

The constructor uses metadata as the stored metadata field by default, so the filter targets metadata.category, not just category. First create a standard index on that field by calling the vector store's create_filter_index method:

vector_store.create_filter_index(
    property_to_filter="metadata.category",
    index_name="category-filter",
)

filtered_engine = index.as_query_engine(
    similarity_top_k=2,
    vector_store_kwargs={
        "pre_filter": {"metadata.category": {"$eq": "ops"}},
    },
)
print(filtered_engine.query("How should I configure my Mongo client?"))

This request restricts vector search to chunks with category="ops". In the sample documents, the connection best practices document matches; the vector indexes document doesn't. If you configure a different metadata_key on the vector store, use that field prefix in both the index and the filter. When composing other query engines or agents, configure this argument on the underlying vector retriever.

View and manage data in Visual Studio Code

You can browse the persisted chunks, embeddings, and vector index without leaving your editor.

  1. Install the Azure DocumentDB extension for Visual Studio Code.

  2. Connect to your Azure DocumentDB cluster from the DocumentDB Connections view by using the same connection string you set as DOCUMENTDB_URI.

  3. Expand the llamaindex_db.documents collection to view chunks, run find queries, and inspect the DiskANN vector index.

    Screenshot of the Azure DocumentDB extension for Visual Studio Code showing a connected cluster with a database and collection of documents in the table view.