Use Haystack with Azure DocumentDB

Haystack is an open-source framework from deepset for building production large language model (LLM) applications. The Haystack integration for Azure DocumentDB provides a document store and retrievers that work directly with Azure DocumentDB.

In this article, you use the integration to:

  • Store Haystack Document objects and their embeddings in Azure DocumentDB.
  • Create an Azure DocumentDB vector index.
  • Retrieve documents with cosmosSearch vector similarity.
  • Build a retrieval-augmented generation (RAG) pipeline with standard Haystack components.

How the integration works

The integration provides the following components:

  • AzureDocumentDBDocumentStore stores Haystack documents, metadata, and embeddings in an Azure DocumentDB collection. It supports synchronous and asynchronous document-store operations.
  • AzureDocumentDBEmbeddingRetriever uses the document store to run cosmosSearch vector queries.
  • AzureDocumentDBFullTextRetriever runs BM25 keyword search. Full-text search is currently a gated preview and must be enabled on your cluster.

The document store uses Microsoft Entra ID through DefaultAzureCredential by default. This authentication flow supports an Azure CLI login for local development and managed identity or workload identity in Azure without changing application code.

Prerequisites

Before you start, complete the following prerequisites:

  • Install Python 3.10 or later.
  • Create an Azure DocumentDB cluster.
  • Enable Microsoft Entra ID authentication and register your identity on the cluster with the readWrite role on the haystack database.
  • Install the Azure CLI and sign in by running az login.
  • Create an Azure OpenAI resource and deploy:
    • text-embedding-3-small for 1,536-dimension embeddings.
    • A chat model such as gpt-4.1-mini.
  • Assign your identity the Cognitive Services OpenAI User role on the Azure OpenAI resource.

This example uses a 1,536-dimension embedding from the text-embedding-3-small model. The embedding dimensions in the vector index must match the selected embedding model.

Install the integration

Install the Azure DocumentDB integration for Haystack. This package installs its required versions of Haystack, Azure Identity, and PyMongo.

python -m pip install azure-documentdb-haystack

Set the cluster name that the document store uses for Microsoft Entra ID authentication.

export AZURE_DOCUMENTDB_CLUSTER_NAME="<cluster-name>"
export AZURE_OPENAI_ENDPOINT="https://<resource-name>.openai.azure.com/"
export AZURE_OPENAI_EMBEDDING_DEPLOYMENT="text-embedding-3-small"
export AZURE_OPENAI_CHAT_DEPLOYMENT="gpt-4.1-mini"

For local development and integration testing, you can instead set AZURE_DOCUMENTDB_CONNECTION_STRING. A connection string can contain credentials, so don't use this option for production workloads.

Create the database and collection

Create the haystack database and documents collection before you initialize the document store. The integration requires both resources to exist.

import os

from azure.identity import DefaultAzureCredential
from pymongo import MongoClient
from pymongo.auth_oidc import (
    OIDCCallback,
    OIDCCallbackContext,
    OIDCCallbackResult,
)


class AzureIdentityTokenCallback(OIDCCallback):
    def __init__(self, credential):
        self.credential = credential

    def fetch(
        self, context: OIDCCallbackContext
    ) -> OIDCCallbackResult:
        token = self.credential.get_token(
            "https://ossrdbms-aad.database.windows.net/.default"
        )
        return OIDCCallbackResult(access_token=token.token)


credential = DefaultAzureCredential()
cluster_name = os.environ["AZURE_DOCUMENTDB_CLUSTER_NAME"]

setup_client = MongoClient(
    (
        f"mongodb+srv://{cluster_name}.global."
        "mongocluster.cosmos.azure.com/"
    ),
    tls=True,
    retryWrites=False,
    authMechanism="MONGODB-OIDC",
    authMechanismProperties={
        "OIDC_CALLBACK": AzureIdentityTokenCallback(credential)
    },
)

database = setup_client["haystack"]
if "documents" not in database.list_collection_names():
    database.create_collection("documents")

setup_client.close()

Initialize the document store

Use the DefaultAzureCredential created in the previous step for Azure DocumentDB and Azure OpenAI. The sample acquires an Azure OpenAI access token when the application starts.

from haystack.utils import Secret
from haystack_integrations.document_stores.azure_documentdb import (
    AzureDocumentDBDocumentStore,
)

azure_openai_token = Secret.from_token(
    credential.get_token(
        "https://cognitiveservices.azure.com/.default"
    ).token
)
azure_openai_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
embedding_deployment = os.environ[
    "AZURE_OPENAI_EMBEDDING_DEPLOYMENT"
]
chat_deployment = os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"]

document_store = AzureDocumentDBDocumentStore(
    database_name="haystack",
    collection_name="documents",
    azure_token_credential=credential,
)

The document-store constructor stores the configuration without connecting to the cluster. When the first document-store operation runs, the integration connects and creates a unique index for the Haystack document id.

Create a vector index

Create a DiskANN vector index on the document embedding field. Run this operation once for the collection.

document_store.create_vector_index(
    dimensions=1536,
    kind="vector-diskann",
    similarity="COS",
    maxDegree=32,
    lBuild=50,
)

DiskANN and HNSW vector indexes require an M30 or higher cluster tier. On a smaller tier, use an IVF index for development:

document_store.create_vector_index(
    dimensions=1536,
    kind="vector-ivf",
    similarity="COS",
    numLists=1,
)

Each embedding field can have only one vector index. For index selection and tuning guidance, see Vector search in Azure DocumentDB.

Embed and write documents

Build an indexing pipeline with OpenAIDocumentEmbedder and Haystack's DocumentWriter. The writer uses AzureDocumentDBDocumentStore instead of inserting records through PyMongo directly.

from haystack import Document, Pipeline
from haystack.components.embedders import AzureOpenAIDocumentEmbedder
from haystack.components.writers import DocumentWriter
from haystack.document_stores.types import DuplicatePolicy

documents = [
    Document(
        id="documentdb-overview",
        content=(
            "Azure DocumentDB is a fully managed, MongoDB-compatible database "
            "with integrated vector search."
        ),
        meta={"title": "Azure DocumentDB overview", "category": "product"},
    ),
    Document(
        id="diskann-guide",
        content=(
            "DiskANN is a vector index for high-recall, low-latency search "
            "on production workloads."
        ),
        meta={"title": "DiskANN vector index", "category": "vector-search"},
    ),
    Document(
        id="authentication-guide",
        content=(
            "The Haystack integration for Azure DocumentDB uses Microsoft "
            "Entra ID authentication by default."
        ),
        meta={"title": "Authentication", "category": "security"},
    ),
]

indexing_pipeline = Pipeline()
indexing_pipeline.add_component(
    "document_embedder",
    AzureOpenAIDocumentEmbedder(
        azure_endpoint=azure_openai_endpoint,
        api_version="2024-02-01",
        azure_deployment=embedding_deployment,
        dimensions=1536,
        api_key=None,
        azure_ad_token=azure_openai_token,
    ),
)
indexing_pipeline.add_component(
    "writer",
    DocumentWriter(
        document_store=document_store,
        policy=DuplicatePolicy.OVERWRITE,
    ),
)
indexing_pipeline.connect("document_embedder.documents", "writer.documents")

indexing_pipeline.run(
    {"document_embedder": {"documents": documents}}
)

For production ingestion, replace the literal documents with Haystack converters such as PyPDFToDocument, MarkdownToDocument, or HTMLToDocument, and use DocumentSplitter to create chunks before embedding them.

Build a RAG pipeline

Create a pipeline that embeds the question, retrieves the most similar documents from Azure DocumentDB, builds a grounded prompt, and generates an answer.

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.embedders import AzureOpenAITextEmbedder
from haystack.components.generators.chat.azure import (
    AzureOpenAIChatGenerator,
)
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.retrievers.azure_documentdb import (
    AzureDocumentDBEmbeddingRetriever,
)

prompt_template = [
    ChatMessage.from_system(
        "Use only the supplied documents to answer the question. "
        "If the documents don't contain the answer, say that you don't know."
    ),
    ChatMessage.from_user(
        """Documents:
{% for document in documents %}
[{{ document.meta.title }}] {{ document.content }}
{% endfor %}
Question: {{ question }}"""
    ),
]

rag_pipeline = Pipeline()
rag_pipeline.add_component(
    "text_embedder",
    AzureOpenAITextEmbedder(
        azure_endpoint=azure_openai_endpoint,
        api_version="2024-02-01",
        azure_deployment=embedding_deployment,
        dimensions=1536,
        api_key=None,
        azure_ad_token=azure_openai_token,
    ),
)
rag_pipeline.add_component(
    "retriever",
    AzureDocumentDBEmbeddingRetriever(
        document_store=document_store,
        top_k=3,
    ),
)
rag_pipeline.add_component(
    "prompt_builder",
    ChatPromptBuilder(
        template=prompt_template,
        required_variables=["question"],
    ),
)
rag_pipeline.add_component(
    "llm",
    AzureOpenAIChatGenerator(
        azure_endpoint=azure_openai_endpoint,
        api_version="2024-12-01-preview",
        azure_deployment=chat_deployment,
        api_key=None,
        azure_ad_token=azure_openai_token,
    ),
)

rag_pipeline.connect(
    "text_embedder.embedding",
    "retriever.query_embedding",
)
rag_pipeline.connect(
    "retriever.documents",
    "prompt_builder.documents",
)
rag_pipeline.connect(
    "prompt_builder.prompt",
    "llm.messages",
)

Ask a question

Run the pipeline. Pass the same question to the text embedder and prompt builder.

question = "Which vector index can I use for production workloads?"

result = rag_pipeline.run(
    {
        "text_embedder": {"text": question},
        "prompt_builder": {"question": question},
    }
)

print(result["llm"]["replies"][0].text)

Filter vector search results

The integration translates Haystack metadata filters into Azure DocumentDB queries and applies them before ranking the nearest neighbors. Create a regular index for every metadata field used in filtered vector search.

document_store.collection.create_index("meta.category")

Pass a Haystack filter to the retriever at initialization or runtime:

query_embedding = AzureOpenAITextEmbedder(
    azure_endpoint=azure_openai_endpoint,
    api_version="2024-02-01",
    azure_deployment=embedding_deployment,
    dimensions=1536,
    api_key=None,
    azure_ad_token=azure_openai_token,
).run(text="How does authentication work?")["embedding"]

retriever = AzureDocumentDBEmbeddingRetriever(
    document_store=document_store,
    top_k=3,
)

result = retriever.run(
    query_embedding=query_embedding,
    filters={
        "field": "meta.category",
        "operator": "==",
        "value": "security",
    },
)

for document in result["documents"]:
    print(document.content, document.score)

For ordered comparisons, filter values must be numbers or ISO-formatted date strings.

Close the document store

Release the underlying PyMongo client when the application shuts down.

document_store.close()

For asynchronous applications, use the integration's asynchronous document-store methods, run_async() on the retriever, and close_async() when the application shuts down.

View data in Visual Studio Code

You can browse the stored documents, embeddings, and vector indexes 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.
  3. Expand the haystack.documents collection to inspect the stored documents and 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.