Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The langchain-azure-cosmosdb package provides Microsoft-maintained LangChain integrations for Azure Cosmos DB and Azure DocumentDB. It includes AzureDocumentDBVectorSearch, a VectorStore implementation that targets the MongoDB-compatible wire protocol exposed by Azure DocumentDB. Use it to embed documents, persist them and their vectors, build DiskANN, HNSW, or IVF indexes, and serve retrieval as a LangChain tool or chain step.
This how-to walks through wiring the integration to your cluster, building a vector index, adding documents, and running similarity and maximal-marginal-relevance (MMR) searches.
What is LangChain?
LangChain is an open-source framework for building applications backed by large language models (LLMs). It provides composable primitives — prompts, chains, retrievers, tools, and agents — for connecting LLMs to your own data and APIs. A common pattern is retrieval-augmented generation (RAG): embed your knowledge base, store the embeddings in a vector store, and at query time retrieve the most relevant chunks to ground the model's answer.
In langchain-azure-cosmosdb, the AzureDocumentDBVectorSearch class wraps a MongoDB collection, performs embeddings via any LangChain Embeddings implementation, and runs vector kNN through the cosmosSearch aggregation stage that Azure DocumentDB supports.
LangChain Azure DocumentDB integration
Azure DocumentDB pairs well with LangChain for the following reasons:
- One store for documents and vectors. Native vector indexing lives alongside document data, enabling RAG and similarity search without introducing a separate vector store. Source documents, metadata, and embeddings stay in the same collection.
- MongoDB-compatible drivers and integrations. Azure DocumentDB exposes the MongoDB wire protocol, so
pymongoand the Microsoft-maintainedlangchain-azure-cosmosdbpackage work against your cluster directly. MongoDB drivers and tools work without application-level rewrites, simplifying migration in common scenarios. - Three index types to match scale.
AzureDocumentDBVectorSearch.create_index(...)supportsvector-ivf,vector-hnsw, andvector-diskann, with optional product quantization (DiskANN) and half-precision (IVF, HNSW) compression for large corpora. - Pre-filter inside vector search. Pass a Mongo filter expression to
pre_filterto narrow candidates insidecosmosSearchrather than post-filtering after kNN, which preserves top-k recall.
Get started: install dependencies
Use Python 3.12 in a virtual environment. Install the vector store integration, an embedding or model provider, and the MongoDB driver.
Before you run the Python examples:
- Create an Azure DocumentDB cluster and allow your development environment to connect. Copy its Connection string from the Azure portal, replace the
<password>placeholder with your URL-encoded cluster password, and then set theDOCUMENTDB_URIenvironment variable. Keep the complete PyMongo connection string, including its connection options. - Set the
OPENAI_API_KEYenvironment variable to an OpenAI API key with access totext-embedding-3-smallandgpt-4o-mini. These examples use the OpenAI API, not Azure OpenAI deployments. Embedding and chat requests can incur charges. - Run the examples in order in the same Python session, and choose only one index tab. Keep the 1,536-dimensional embedding model and vector index dimensions aligned.
pip install langchain-azure-cosmosdb langchain-core langchain-openai pymongo
Note
The vector store integration in langchain-azure-cosmosdb is Python-only. If you're building a TypeScript app, use the mongodb driver and run vector queries with the same $search + cosmosSearch aggregation pipeline shown in Vector search in Azure DocumentDB.
Connect to Azure DocumentDB and create a vector store
Use the from_connection_string factory to get a vector store bound to a database.collection namespace and a LangChain embeddings model.
import os
from uuid import uuid4
from langchain_azure_cosmosdb import (
AzureDocumentDBVectorSearch,
)
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small") # 1536 dimensions
# Use a new demo collection so existing application data is not changed.
collection_name = f"knowledge_base_demo_{uuid4().hex}"
vector_store = AzureDocumentDBVectorSearch.from_connection_string(
connection_string=os.environ["DOCUMENTDB_URI"],
namespace=f"ragdb.{collection_name}",
embedding=embeddings,
index_name="kb_vector_index",
)
Key constructor parameters:
| Parameter | Default | Purpose |
|---|---|---|
namespace |
required | database.collection to back the store. |
embedding |
required | Any LangChain Embeddings implementation. |
index_name |
vectorSearchIndex |
Name of the vector index to create or reuse. |
text_key |
textContent |
Field that stores the raw text. |
embedding_key |
vectorContent |
Field that stores the vector. |
Create a vector index
Choose an index type that matches your dataset size and accuracy needs. All three types use the same create_index method. The kind argument selects the algorithm. Each tab sets index_kind, which later queries reuse. For this three-document demo, IVF with num_lists=1 is sufficient.
Important
The connection example selects a new collection on each run. Keep this isolated demo namespace rather than pointing the sample at an application collection. The guard in each tab stops if the named vector index already exists. To rerun the sample, don't delete or replace an existing index. Choose a new demo collection to try another index type.
from langchain_azure_cosmosdb import (
AzureDocumentDBSimilarityType,
AzureDocumentDBVectorSearchType,
)
index_kind = AzureDocumentDBVectorSearchType.VECTOR_DISKANN
if vector_store.index_exists():
raise RuntimeError("The demo vector index already exists. Use a new collection.")
vector_store.create_index(
kind=index_kind,
dimensions=1536,
similarity=AzureDocumentDBSimilarityType.COS,
max_degree=32,
l_build=50,
)
For pre-filter queries, also create a regular index on each filterable property. The integration stores user metadata in a nested metadata object, so both the index and query filter must use metadata.category:
vector_store.create_filter_index(property_to_filter="metadata.category", index_name="category_idx")
Add documents to the store
add_texts and add_documents embed the text on the client and bulk-insert the resulting documents into the collection.
texts = [
"DocumentDB supports DiskANN for high-recall vector search.",
"HNSW is suitable for medium-scale embedding indexes.",
"IVF is the lowest-cost option for prototypes and small datasets.",
]
metadatas = [
{"category": "rag", "source": "docs"},
{"category": "rag", "source": "docs"},
{"category": "rag", "source": "docs"},
]
ids = vector_store.add_texts(texts=texts, metadatas=metadatas)
Run a similarity search
similarity_search returns the top-k most similar documents. similarity_search_with_score returns the same documents paired with their similarity score.
results = vector_store.similarity_search(
query="Which vector index should I use for a million embeddings?",
k=3,
kind=index_kind,
pre_filter={"metadata.category": {"$eq": "rag"}},
)
for doc in results:
print(doc.page_content, doc.metadata)
pre_filter runs inside the cosmosSearch stage, preserving top-k accuracy when narrowing the candidate set by metadata.
Diversify results with MMR
Maximal-marginal-relevance (MMR) re-ranks the top-fetch_k results to balance relevance against diversity. Use it to avoid near-duplicates dominating the result set.
diverse = vector_store.max_marginal_relevance_search(
query="vector index trade-offs",
k=4,
fetch_k=20,
lambda_mult=0.5, # 0.0 = max diversity, 1.0 = max relevance
kind=index_kind,
)
for doc in diverse:
print(doc.page_content)
Use the vector store as a retriever
Convert the store into a LangChain Retriever and plug it into any chain or agent:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
retriever = vector_store.as_retriever(
search_type="similarity",
search_kwargs={
"k": 4,
"kind": index_kind,
},
)
prompt = ChatPromptTemplate.from_template(
"Answer using only the context.\n\nContext:\n{context}\n\nQuestion: {question}"
)
llm = ChatOpenAI(model="gpt-4o-mini")
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
)
print(chain.invoke("Which vector index should I use for a million embeddings?").content)
View and manage data in Visual Studio Code
You can browse persisted documents and vector indexes interactively without leaving your editor.
Install the Azure DocumentDB extension for Visual Studio Code.
Connect to your Azure DocumentDB cluster from the DocumentDB Connections view by using the same connection string you set as
DOCUMENTDB_URI.Expand your database to view collections, run find queries, and inspect vector and filter indexes that the vector store created.
Before you close the Python session, record the generated collection_name. When you finish, use the connected management tool to verify that exact name and remove only the demo collection and its indexes. Preserve unrelated collections, the database, and any shared cluster. Each run creates a new demo collection, so repeat this cleanup only for collections you created for this exercise. Removing demo data doesn't deprovision the Azure DocumentDB cluster; cluster charges can continue while it remains provisioned.