Skip to content

RAG Data Preparation: The Foundation That Makes or Breaks Your AI System

Preparing data for RAG systems: document parsing, token-based chunking, contextual enrichment with prompt caching, embedding choice and keeping the index in sync

Ayhan Sipahi Ayhan Sipahi

Most RAG implementation failures trace back to data preparation, not retrieval architecture. Teams spend weeks tuning retrieval parameters when the real problem is poorly parsed documents or inappropriate chunking. Validated parsing plus recursive splitting at around 512 tokens is the default worth starting from; semantic and parent-child chunking earn their extra cost only once measurements say they do.

The Quality Ceiling of a RAG Pipeline#

There is a common pattern in RAG implementations: sophisticated retrieval architectures (hybrid search, reranking, CRAG) that still produce poor results. The root cause is almost always upstream in the data preparation layer.

RAG Architecture Layer

Data Preparation Layer

Quality Ceiling

Document Parsing

Text Preprocessing

Chunking Strategy

Metadata Enrichment

Embedding Generation

Hybrid Search

Reranking

Quality Checks

Retrieval can only rank what data preparation put into the index. If parsing drops a table or chunking cuts a definition in half, hybrid search and reranking have no correct passage to surface. Their gains stop at whatever the prepared data allows. When retrieval quality is poor, inspect the stored chunks before tuning the retriever.

Document Parsing: Extracting Clean Text from Messy Sources#

Real-world documents are messy. PDFs store text as positioned glyphs, so reading order has to be reconstructed, tables get mangled, and multi-column layouts require layout analysis before extraction. Scanned documents add OCR errors on top of all that.

Parsing Tool Selection#

ToolLayout and TablesRunsBest For
DoclingPage layout, reading order and table structure; OCR for scanned PDFsLocallyComplex documents, sensitive data
LlamaParseGenerative-model parsing into markdown, text or JSONLlamaIndex APITeams that accept a hosted parser
UnstructuredStrategies from rule-based fast to layout-model hi_res and ocr_only; optional table structure inferenceLocallyOCR-heavy, mixed formats
PyMuPDF/PyPDFEmbedded text layer; PyMuPDF adds find_tables()LocallySimple digital PDFs

Table extraction is where these tools differ most, and published accuracy figures rarely transfer to your documents. Run each candidate on the same sample of your own files and compare the tables by hand.

Practical PDF Parsing#

from docling.document_converter import DocumentConverter
from docling_core.types.doc import SectionHeaderItem, TableItem, TextItem

converter = DocumentConverter()

# Parse PDF with layout analysis
result = converter.convert("technical-manual.pdf")
doc = result.document

# Walk the document in reading order
current_section = None
for item, _level in doc.iterate_items():
    if isinstance(item, SectionHeaderItem):
        # Check headers first: SectionHeaderItem is a TextItem subclass
        current_section = item.text
    elif isinstance(item, TableItem):
        # Table extracted with structure preserved
        markdown_table = item.export_to_markdown(doc=doc)
    elif isinstance(item, TextItem):
        # Text with its nearest section header
        text = item.text
        section = current_section

# Export as markdown for RAG ingestion
markdown_output = doc.export_to_markdown()

The markdown export keeps headings as # lines and separates paragraphs with blank lines. Keep that structure through every later step, because the recursive chunker below splits on exactly those line breaks.

HTML Content Extraction#

from bs4 import BeautifulSoup
from readability import Document

def extract_html_content(html: str) -> dict:
    """Extract meaningful content from HTML, handling diverse structures."""

    # Use readability for main content extraction
    doc = Document(html)
    main_content = doc.summary()
    title = doc.title()

    # Parse with BeautifulSoup for structure
    soup = BeautifulSoup(main_content, 'html.parser')

    # Remove navigation, ads, footers
    for element in soup.find_all(['nav', 'footer', 'aside', 'script', 'style']):
        element.decompose()

    # Extract text with structure preservation
    text_blocks = []
    for element in soup.find_all(['h1', 'h2', 'h3', 'p', 'li', 'td']):
        text = element.get_text(strip=True)
        if text:
            text_blocks.append({
                'type': element.name,
                'text': text,
                'level': int(element.name[1]) if element.name.startswith('h') else 0
            })

    return {
        'title': title,
        'blocks': text_blocks,
        'full_text': soup.get_text(separator='\n', strip=True)
    }

Tip

Start with rule-based parsing before resorting to LLM-based parsing. Use hybrid approaches: heuristics for structure combined with Vision-Language Models only for the most challenging elements.

Text Preprocessing: Cleaning for Embedding Quality#

Embeddings encode noise along with signal. Inconsistent formatting creates spurious similarity. PII in embeddings creates security risks. Preprocessing removes these issues before they propagate through the pipeline.

import re
from typing import List
import unicodedata

class TextPreprocessor:
    def __init__(self):
        self.pii_patterns = {
            'email': r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b',
            'phone': r'\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b',
            'ssn': r'\b\d{3}-\d{2}-\d{4}\b',
            # 13-16 digits covers 15-digit Amex too, and also hits some order numbers
            'credit_card': r'\b(?:\d[ -]?){12,15}\d\b',
        }

    def normalize_whitespace(self, text: str) -> str:
        """Collapse spaces and tabs but keep line and paragraph breaks."""
        text = text.replace('\r\n', '\n')
        text = re.sub(r'[ \t]+', ' ', text)
        text = re.sub(r' *\n *', '\n', text)    # trim spaces around line breaks
        text = re.sub(r'\n{3,}', '\n\n', text)  # at most one blank line
        return text.strip()

    def normalize_unicode(self, text: str) -> str:
        """Normalize unicode characters to consistent form."""
        return unicodedata.normalize('NFKC', text)

    def redact_pii(self, text: str) -> str:
        """Detect and redact PII patterns."""
        for pii_type, pattern in self.pii_patterns.items():
            text = re.sub(pattern, f'[REDACTED_{pii_type.upper()}]', text)
        return text

    def remove_boilerplate(self, text: str, patterns: List[str] = None) -> str:
        """Remove known boilerplate text patterns."""
        default_patterns = [
            r'Page \d+ of \d+',
            r'Copyright \d{4}.*?(?=\n|$)',
            r'All rights reserved\.?',
        ]
        patterns = patterns or default_patterns
        for pattern in patterns:
            text = re.sub(pattern, '', text, flags=re.IGNORECASE)
        return text

    def process(self, text: str, redact_pii: bool = True) -> str:
        """Run full preprocessing pipeline."""
        text = self.normalize_unicode(text)
        text = self.remove_boilerplate(text)
        text = self.normalize_whitespace(text)
        if redact_pii:
            text = self.redact_pii(text)
        return text

Feed process() the markdown export from the parser. Whitespace normalization only collapses runs of spaces and tabs, so headings and paragraph breaks reach the chunker intact. The common one-liner re.sub(r'\s+', ' ', text) turns every document into a single line, and the recursive splitter then has no paragraph boundary left to respect.

Warning

redact_pii is a best-effort filter. The patterns cover US-style phone and SSN formats, 13-16 digit card numbers and email addresses. Names, street addresses and identifiers written in prose pass straight through. When PII must stay out of the index, use a dedicated detector such as Presidio, which combines named entity recognition, regular expressions, rule-based logic and checksums. Even Presidio’s documentation says it cannot guarantee finding all sensitive information, so treat any detector as one layer among several.

Deduplication#

Near-duplicate content both wastes storage and skews retrieval results. MinHash LSH provides efficient near-duplicate detection:

from datasketch import MinHash, MinHashLSH
import hashlib
from typing import List, Set

class Deduplicator:
    def __init__(self, threshold: float = 0.8, num_perm: int = 128):
        self.threshold = threshold
        self.num_perm = num_perm
        self.lsh = MinHashLSH(threshold=threshold, num_perm=num_perm)
        self.exact_hashes: Set[str] = set()
        self.doc_id = 0

    def _compute_minhash(self, text: str) -> MinHash:
        """Compute MinHash signature for text."""
        minhash = MinHash(num_perm=self.num_perm)
        words = text.lower().split()
        for i in range(len(words) - 2):
            shingle = ' '.join(words[i:i+3])
            minhash.update(shingle.encode('utf-8'))
        return minhash

    def is_duplicate(self, text: str) -> bool:
        """Check for exact or near duplicates."""
        # Exact duplicate check
        text_hash = hashlib.md5(text.encode()).hexdigest()
        if text_hash in self.exact_hashes:
            return True
        self.exact_hashes.add(text_hash)

        # Fewer than 3 words yields no shingles, and empty signatures
        # would all match each other; the exact check above covers these
        if len(text.split()) < 3:
            return False

        # Near-duplicate check
        minhash = self._compute_minhash(text)
        if self.lsh.query(minhash):
            return True

        self.lsh.insert(f"doc_{self.doc_id}", minhash)
        self.doc_id += 1
        return False

    def deduplicate(self, documents: List[str]) -> List[str]:
        """Remove duplicates from document list."""
        return [doc for doc in documents if not self.is_duplicate(doc)]

Chunking Strategies#

Chunking determines how information is organized for retrieval. The core tension: too small loses context, too large dilutes relevance signal.

Strategy Comparison#

Chunking Strategies

Upgrade

Upgrade

Alternative

Fixed-Size Simple, fast Ignores structure

Recursive Respects boundaries Good default

Semantic Topic-aware splits Requires embeddings

Parent-Child Better context Extra parent storage

from langchain_text_splitters import RecursiveCharacterTextSplitter

def recursive_chunking(text: str, chunk_size: int = 512, overlap: int = 50) -> list:
    """
    Split text recursively using hierarchy of separators.
    Tries to keep paragraphs together, then sentences, then words.
    chunk_size and overlap count tokens.
    """
    splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
        encoding_name="cl100k_base",  # tokenizer of OpenAI text-embedding-3 models
        chunk_size=chunk_size,
        chunk_overlap=overlap,
        separators=[
            "\n\n",  # Paragraphs first
            "\n",  # Then line breaks
            ". ",  # Then sentences
            ", ",  # Then clauses
            " ",  # Finally words
        ],
    )
    return splitter.split_text(text)

The plain constructor measures length with len, which counts characters. A 512-character chunk holds far fewer than 512 tokens, so a token-sized recommendation applied through len produces chunks much smaller than intended. from_tiktoken_encoder measures with a tokenizer and splits any piece that is still too large again. Its default encoding is gpt2, so name the encoding explicitly, and pick the tokenizer of the embedding model you use when it is not an OpenAI model.

Semantic Chunking#

from langchain_experimental.text_splitter import SemanticChunker
from langchain_openai.embeddings import OpenAIEmbeddings

def semantic_chunking(text: str) -> list:
    """
    Split based on semantic similarity between sentences.
    Groups semantically related content together.
    """
    embeddings = OpenAIEmbeddings(model="text-embedding-3-small")

    splitter = SemanticChunker(
        embeddings=embeddings,
        breakpoint_threshold_type="percentile",
        breakpoint_threshold_amount=95,  # Split at top 5% dissimilarity
        min_chunk_size=100
    )

    return splitter.split_text(text)

# Trade-off: Requires embedding calls during chunking

Semantic chunking costs an embedding call per sentence before indexing even starts, and the payoff is not guaranteed. A comparison of semantic and fixed-size chunking across retrieval tasks found no consistent advantage for the semantic variant and concluded that its computational cost was not justified (Qu, Tu and Bao). Treat it as an experiment to run against your own test set once recursive splitting is in place.

Hierarchical Parent-Child Chunking#

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.retrievers import ParentDocumentRetriever
from langchain.storage import InMemoryStore
from langchain_chroma import Chroma

def setup_hierarchical_chunking(documents: list, embeddings):
    """
    Create parent-child hierarchy for precision + context.
    Search on small child chunks, return large parent chunks.
    """
    # Sizes here count characters (the default length_function=len)
    # Parent splitter: large chunks for context
    parent_splitter = RecursiveCharacterTextSplitter(
        chunk_size=2000,
        chunk_overlap=200
    )

    # Child splitter: small chunks for precise retrieval
    child_splitter = RecursiveCharacterTextSplitter(
        chunk_size=400,
        chunk_overlap=50
    )

    # Storage for parent documents
    docstore = InMemoryStore()

    # Vector store indexes child chunks
    vectorstore = Chroma(
        collection_name="child_chunks",
        embedding_function=embeddings
    )

    # Retriever searches children, returns parents
    retriever = ParentDocumentRetriever(
        vectorstore=vectorstore,
        docstore=docstore,
        child_splitter=child_splitter,
        parent_splitter=parent_splitter
    )

    retriever.add_documents(documents)
    return retriever

# Performance: Improved relevance on structured documents by preserving context
# Trade-off: Every parent chunk is stored in the docstore next to the child vectors

Chunk Size Guidelines#

All sizes below count tokens, measured with the embedding model’s tokenizer. They are starting points to tune against your retrieval test set.

Content TypeSize (tokens)Overlap (tokens)Rationale
Technical docs51250-100Balance detail with context
Conversational25625-50Shorter exchanges
Legal/contracts1024100-150Preserve clause context
CodeOne function or classNone at function boundariesKeep functions intact
Q&A pairs128-2560Each Q&A is self-contained

For code, split on language syntax first; RecursiveCharacterTextSplitter.from_language ships separator lists for common languages.

Contextual Chunking: The Lost Context Problem#

Traditional chunking destroys document context. A chunk saying “This approach reduces latency by 40%” is useless without knowing which approach. Contextual chunking addresses this.

Full Document

Parse Document

Create Chunks

Traditional Approach

Contextual Approach

Embed Chunk

Lost Context: 'It reduces latency by 40%'

Add Context via LLM

Embed Contextualized Chunk

Preserved Context: 'This section discusses caching. It reduces latency by 40%'

Poor Retrieval

Accurate Retrieval

Anthropic’s Contextual Retrieval Technique#

from anthropic import Anthropic
from typing import List

CHUNK_PROMPT = """Here is a chunk from that document:
<chunk>
{chunk}
</chunk>

Provide a short context (2-3 sentences) to situate this chunk within the document. Focus on:
1. What section/topic this chunk belongs to
2. Key entities or concepts being discussed
3. How it relates to the document's main subject

Answer only with the context."""


def add_contextual_headers(
    document: str,
    chunks: List[str],
    model: str = "claude-haiku-5-5"
) -> List[str]:
    """
    Prepend chunk-specific context using Claude.
    The document block is cached: the first call writes it to the cache,
    later calls for the same document read it at a fraction of the input price.
    """
    client = Anthropic()
    contextualized_chunks = []

    for chunk in chunks:
        response = client.messages.create(
            model=model,
            max_tokens=200,
            # Haiku 5.5 thinks by default; a short summary needs no reasoning tokens.
            # Some models reject "disabled", so check before switching models.
            thinking={"type": "disabled"},
            messages=[{
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": f"Here is the full document:\n<document>\n{document}\n</document>",
                        "cache_control": {"type": "ephemeral"},
                    },
                    {"type": "text", "text": CHUNK_PROMPT.format(chunk=chunk)},
                ],
            }],
        )

        context = next(block.text for block in response.content if block.type == "text")
        contextualized_chunks.append(f"{context}\n\n{chunk}")

    return contextualized_chunks

Anthropic measured the effect on the top-20-chunk retrieval failure rate. Contextual embeddings alone cut failures by 35%. Adding BM25 brought the reduction to 49%, and a reranking step on top reached 67%. The 49% setup is Contextual BM25: the same contextualized text goes into both the embedding index and the BM25 index. Feed contextualized_chunks to both indexes; a BM25 index over the raw chunks is a different setup from the one measured.

The cost argument rests on prompt caching. Without caching, every call pays full input price for the whole document, so a document split into 10 chunks is billed as input 10 times. With the cache_control block, the first call writes the document to the cache at 1.25 times the base input price and the following calls read it at 0.1 times. Anthropic’s own estimate of $1.02 per million document tokens assumed 800-token chunks, 8k-token documents, 50 tokens of instructions and 100 tokens of generated context, priced for Claude 3 Haiku. Claude Haiku 5.5 charges $0.10 input, $0.125 cache write, $0.01 cache read and $0.50 output per million tokens for prompts up to 100,000 tokens; longer prompts are billed at five times these rates. The same assumptions at these prices work out as follows:

Per million document tokens (125 documents, 1,250 calls)Without cachingWith caching
Document tokens billed as input10,000,000 at $0.101,000,000 written at $0.125 + 9,000,000 read at $0.01
Chunk and instruction tokens1,062,500 at $0.101,062,500 at $0.10
Generated context125,000 at $0.50125,000 at $0.50
Totalabout $1.17about $0.38

Two conditions keep the cache working. The document must reach the model’s minimum cacheable length (512 tokens on Haiku 5.5); shorter prompts run uncached without an error. The cache entry also becomes available only after the first response starts, so send the first chunk of each document before fanning out the rest in parallel. The default cache lifetime is 5 minutes, refreshed on each hit, which is plenty for a sequential loop over one document’s chunks.

Rule-Based Context (Zero-Cost Alternative)#

def add_structural_context(chunks: List[dict]) -> List[dict]:
    """
    Add context based on document structure without LLM calls.
    Uses metadata from structure-aware chunking.
    """
    contextualized = []

    for chunk in chunks:
        metadata = chunk.get('metadata', {})
        content = chunk['content']

        context_parts = []
        if 'document_title' in metadata:
            context_parts.append(f"From: {metadata['document_title']}")
        if 'header_1' in metadata:
            context_parts.append(f"Section: {metadata['header_1']}")
        if 'header_2' in metadata:
            context_parts.append(f"Subsection: {metadata['header_2']}")

        context = " | ".join(context_parts)
        contextualized.append({
            'content': f"{context}\n\n{content}" if context else content,
            'metadata': metadata
        })

    return contextualized

Embedding Model Selection#

Choosing the right embedding model depends on content type, chunk size, and deployment constraints. The table leaves benchmark scores out on purpose. Vendor figures come from the benchmark version each vendor ran at launch: OpenAI’s guide still lists 62.3% and 64.6% average MTEB scores for its two text-embedding-3 models. MTEB has since expanded into MMTEB, with more than 500 tasks in over 250 languages, so scores from different versions do not line up in one column. Use the current leaderboard to build a shortlist, then decide with your own test queries.

ModelDimensionsPrice per 1M tokensBest For
Cohere embed-v4.0256, 512, 1024, 1536 (default)See Cohere pricingMixed text and image documents such as PDFs
text-embedding-3-large3072, shorter via dimensions$0.13General purpose
text-embedding-3-small1536, shorter via dimensions$0.02Cost-sensitive
Voyage voyage-4-large1024 (default), 256, 512, 2048$0.12General-purpose retrieval
BGE-M31024Self-hostedPrivacy-critical, 100+ languages

Embedding Optimization#

from typing import List
import numpy as np
from openai import OpenAI

client = OpenAI()

def get_embeddings(
    texts: List[str],
    dimensions: int = 1024
) -> List[List[float]]:
    """
    Get OpenAI embeddings with dimension reduction.
    On MTEB, 256-dim text-embedding-3-large still beats full-size ada-002.
    """
    response = client.embeddings.create(
        model="text-embedding-3-large",
        input=texts,
        dimensions=dimensions  # Matryoshka truncation
    )
    return [item.embedding for item in response.data]


def batch_embed_with_normalization(
    texts: List[str],
    batch_size: int = 100,
    dimensions: int = 1024
) -> np.ndarray:
    """
    Embed texts in batches with L2 normalization.
    Normalization enables cosine similarity via dot product.
    OpenAI already returns unit-length vectors, so for them this step is
    a harmless no-op; keep it for models that do not normalize.
    """
    all_embeddings = []

    for i in range(0, len(texts), batch_size):
        batch = texts[i:i + batch_size]
        embeddings = get_embeddings(batch, dimensions)
        all_embeddings.extend(embeddings)

    embeddings_array = np.array(all_embeddings)

    # L2 normalize for cosine similarity
    norms = np.linalg.norm(embeddings_array, axis=1, keepdims=True)
    return embeddings_array / norms

Metadata Extraction and Enrichment#

Metadata enables filtering before semantic search, provides ranking signals, and supports source attribution.

from dataclasses import dataclass
from typing import List, Optional
from datetime import datetime

@dataclass
class ChunkMetadata:
    # Content-based
    keywords: List[str]
    entities: List[str]
    content_type: str

    # Structural
    document_title: str
    section_header: Optional[str]
    chunk_index: int

    # Contextual
    source_url: Optional[str]
    ingestion_date: datetime
    language: str

    # Technical
    word_count: int
    has_code: bool
    has_table: bool

Automated Extraction#

import spacy
from collections import Counter
from typing import Dict, List

class MetadataExtractor:
    def __init__(self):
        self.nlp = spacy.load("en_core_web_sm")

    def extract_entities(self, text: str) -> Dict[str, List[str]]:
        """Extract named entities using spaCy."""
        doc = self.nlp(text)
        entities = {}
        for ent in doc.ents:
            if ent.label_ not in entities:
                entities[ent.label_] = []
            entities[ent.label_].append(ent.text)
        return entities

    def extract_keywords(self, text: str, top_n: int = 10) -> List[str]:
        """Extract keywords using noun chunks."""
        doc = self.nlp(text)
        noun_chunks = [chunk.text.lower() for chunk in doc.noun_chunks]
        chunk_counts = Counter(noun_chunks)
        return [word for word, _ in chunk_counts.most_common(top_n)]

    def detect_content_type(self, text: str) -> str:
        """Heuristic content type detection."""
        code_patterns = ['def ', 'function ', 'class ', 'import ', '```']
        if any(pattern in text for pattern in code_patterns):
            return 'code'

        tech_indicators = ['API', 'database', 'server', 'deployment']
        if sum(1 for ind in tech_indicators if ind.lower() in text.lower()) >= 2:
            return 'technical'

        return 'general'

Storing with Vector Database#

import hashlib
import uuid
from typing import List, Optional

from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")

# Any fixed UUID works; generate it once and never change it
CORPUS_NAMESPACE = uuid.UUID("2f0f8a52-7a3e-4c55-9a8e-3b8d6d1c0e41")


def chunk_point_id(doc_id: str, chunk_text: str) -> str:
    """Stable id: the same document and chunk text always map to the same point."""
    digest = hashlib.sha256(chunk_text.encode("utf-8")).hexdigest()
    return str(uuid.uuid5(CORPUS_NAMESPACE, f"{doc_id}:{digest}"))


def ensure_collection(collection_name: str, dim: int) -> None:
    """Create the collection once; never drop existing data."""
    if client.collection_exists(collection_name):
        return
    client.create_collection(
        collection_name=collection_name,
        vectors_config=models.VectorParams(size=dim, distance=models.Distance.COSINE),
    )
    # Per-document filters and deletes run on doc_id
    client.create_payload_index(
        collection_name=collection_name,
        field_name="doc_id",
        field_schema=models.PayloadSchemaType.KEYWORD,
    )


def store_chunks_with_metadata(
    doc_id: str,
    chunks: List[str],
    embeddings: List[List[float]],
    metadata_list: List[dict],
    collection_name: str = "documents",
) -> None:
    """Store one document's chunks with rich metadata in Qdrant."""
    ensure_collection(collection_name, len(embeddings[0]))

    points = [
        models.PointStruct(
            id=chunk_point_id(doc_id, chunk),
            vector=embedding,
            payload={"doc_id": doc_id, "chunk_index": idx, "text": chunk, **metadata},
        )
        for idx, (chunk, embedding, metadata)
        in enumerate(zip(chunks, embeddings, metadata_list))
    ]

    client.upsert(collection_name=collection_name, points=points)


def search_with_filter(
    query_embedding: List[float],
    collection_name: str,
    content_type: Optional[str] = None,
    top_k: int = 10,
) -> List[dict]:
    """Search with optional metadata filter."""
    query_filter = None
    if content_type:
        query_filter = models.Filter(
            must=[models.FieldCondition(
                key="content_type",
                match=models.MatchValue(value=content_type),
            )]
        )

    response = client.query_points(
        collection_name=collection_name,
        query=query_embedding,
        query_filter=query_filter,
        limit=top_k,
        with_payload=True,
    )

    return [{"text": point.payload["text"], "score": point.score} for point in response.points]

recreate_collection drops all data on every call and is deprecated; checking collection_exists before create_collection keeps earlier batches. Point ids derived from the document id and the chunk text replace enumerate indexes, which restart at 0 for every batch and overwrite points from other documents. The same id scheme drives incremental updates in the next section. Queries go through query_points, the client’s universal search endpoint.

Keeping the Index in Sync#

Documents change after the first ingest: pages get edited, files get deleted, and sooner or later the embedding model changes. Treating ingestion as a one-off job leaves stale chunks in the index, and retrieval then returns text that no longer exists in the source.

Because a point id is a hash of the document id and the chunk text, an unchanged chunk keeps its id across re-ingests. That gives three cheap operations: reuse the vector for chunks that already exist, embed only new text, and delete whatever the new version no longer contains.

from typing import Callable, List

from qdrant_client import models


def delete_document(doc_id: str, collection_name: str = "documents") -> None:
    """Remove every chunk of a document that left the corpus."""
    client.delete(
        collection_name=collection_name,
        points_selector=models.FilterSelector(
            filter=models.Filter(must=[
                models.FieldCondition(key="doc_id", match=models.MatchValue(value=doc_id)),
            ])
        ),
    )


def sync_document(
    doc_id: str,
    chunks: List[str],
    metadata_list: List[dict],
    embed: Callable[[List[str]], List[List[float]]],
    collection_name: str = "documents",
) -> int:
    """Align one document's chunks with its latest version. Returns the number embedded."""
    if not chunks:
        delete_document(doc_id, collection_name)
        return 0

    ids = [chunk_point_id(doc_id, chunk) for chunk in chunks]

    # Reuse stored vectors for chunk text that is already indexed
    stored = client.retrieve(collection_name=collection_name, ids=ids, with_vectors=True)
    vectors = {str(point.id): point.vector for point in stored}

    missing = [i for i, point_id in enumerate(ids) if point_id not in vectors]
    if missing:
        for i, vector in zip(missing, embed([chunks[i] for i in missing])):
            vectors[ids[i]] = vector

    # Upsert all chunks so chunk_index and metadata reflect the new version
    client.upsert(
        collection_name=collection_name,
        points=[
            models.PointStruct(
                id=point_id,
                vector=vectors[point_id],
                payload={"doc_id": doc_id, "chunk_index": idx, "text": chunks[idx], **metadata_list[idx]},
            )
            for idx, point_id in enumerate(ids)
        ],
    )

    # Delete chunks of this document that the new version no longer contains
    client.delete(
        collection_name=collection_name,
        points_selector=models.FilterSelector(
            filter=models.Filter(
                must=[models.FieldCondition(key="doc_id", match=models.MatchValue(value=doc_id))],
                must_not=[models.HasIdCondition(has_id=ids)],
            )
        ),
    )
    return len(missing)

The upsert runs before the delete, so a query that arrives mid-sync sees the old and new chunks together for a moment, never an empty document.

Contextual headers change how ids should be derived. Each context comes from an LLM call over the full document, so editing one paragraph can change the context of every chunk. If the id hashes the contextualized text, an edited document gets all new ids. The sync then repeats every LLM call just to compute them, and re-embeds the whole document. Derive the id from the raw chunk text plus a version tag for the context prompt instead, for example chunk_point_id(doc_id, f"{CONTEXT_PROMPT_VERSION}:{chunk}"), and store the generated context in the payload next to the chunk text. Only chunks with missing ids then go through add_contextual_headers and the embedding model. The trade-off is that an unchanged chunk keeps its old context after the rest of the document changes. Bump the version whenever CHUNK_PROMPT changes, and the next sync regenerates every context. When a document’s overall subject changes, add a per-document revision to the same tag, for example f"{CONTEXT_PROMPT_VERSION}:{context_rev}:{chunk}", and bump context_rev. The next sync then regenerates every context of that document, and its old chunks stay searchable until the final delete step.

A new embedding model needs a new collection. Its vectors live in a different space from the old ones, and the size often differs too (3072 for text-embedding-3-large, 1024 for BGE-M3), so the old collection cannot hold them. Create the new collection next to the live one with ensure_collection, because sync_document expects it to exist (on a first ingest too). Run every document through sync_document with the new model, then move the alias the application queries:

def switch_alias(alias: str, new_collection: str) -> None:
    """Point queries at a rebuilt collection in one atomic step."""
    client.update_collection_aliases(
        change_aliases_operations=[
            # Skip the delete on first setup, when the alias does not exist yet
            models.DeleteAliasOperation(delete_alias=models.DeleteAlias(alias_name=alias)),
            models.CreateAliasOperation(
                create_alias=models.CreateAlias(collection_name=new_collection, alias_name=alias)
            ),
        ]
    )

Qdrant applies alias changes atomically, so no query sees a half-built index. Keep the old collection until the retrieval evaluation in the next section confirms the new model on your own test queries.

Quality Metrics for Data Preparation#

Measuring data quality enables data-driven optimization and early issue detection.

import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from typing import List

def evaluate_chunk_coherence(chunks: List[str], embedding_model) -> dict:
    """
    Measure semantic coherence within chunks.
    High coherence = chunk discusses single topic.
    """
    coherence_scores = []

    for chunk in chunks:
        sentences = chunk.split('. ')
        if len(sentences) < 2:
            coherence_scores.append(1.0)
            continue

        embeddings = np.array(embedding_model.embed(sentences))
        similarities = cosine_similarity(embeddings)

        n = len(sentences)
        coherence = (similarities.sum() - n) / (n * (n - 1)) if n > 1 else 1.0
        coherence_scores.append(coherence)

    return {
        'mean_coherence': np.mean(coherence_scores),
        'min_coherence': np.min(coherence_scores),
        'low_coherence_count': sum(1 for s in coherence_scores if s < 0.5)
    }


def evaluate_boundary_quality(chunks: List[str]) -> dict:
    """Check if chunks have clean boundaries."""
    bad_starts = 0
    bad_ends = 0

    lowercase_starters = ['and', 'but', 'or', 'so', 'because', 'however']

    for chunk in chunks:
        first_word = chunk.split()[0].lower() if chunk.split() else ''
        if first_word in lowercase_starters:
            bad_starts += 1

        if chunk and chunk.rstrip()[-1] not in '.!?:':
            bad_ends += 1

    return {
        'bad_start_ratio': bad_starts / len(chunks),
        'bad_end_ratio': bad_ends / len(chunks),
        'clean_boundary_ratio': 1 - (bad_starts + bad_ends) / (2 * len(chunks))
    }


def evaluate_retrieval_quality(
    embeddings: np.ndarray,
    test_queries: List[str],
    relevant_chunk_ids: List[List[int]],
    embedding_model
) -> dict:
    """Evaluate embedding quality using retrieval tests."""
    query_embeddings = np.array(embedding_model.embed(test_queries))
    similarities = cosine_similarity(query_embeddings, embeddings)

    hits_at_k = {1: 0, 5: 0, 10: 0}
    mrr_sum = 0

    for i, relevant_ids in enumerate(relevant_chunk_ids):
        ranked_indices = np.argsort(similarities[i])[::-1]

        for rank, idx in enumerate(ranked_indices):
            if idx in relevant_ids:
                mrr_sum += 1 / (rank + 1)
                for k in hits_at_k:
                    if rank < k:
                        hits_at_k[k] += 1
                break

    n_queries = len(test_queries)
    return {
        'mrr': mrr_sum / n_queries,
        'hit_rate@1': hits_at_k[1] / n_queries,
        'hit_rate@5': hits_at_k[5] / n_queries,
        'hit_rate@10': hits_at_k[10] / n_queries
    }

Common Pitfalls and Solutions#

Pitfall 1: Skipping Parsing Validation#

Assuming parsing tools work perfectly on all documents leads to missing content and mangled tables in retrieval results. Always validate parsing output on representative samples before full ingestion.

Pitfall 2: One-Size-Fits-All Chunking#

Using the same chunk size for all content types results in code split mid-function and tables losing context. Match chunking strategy to content structure.

Pitfall 3: Ignoring Lost Context#

Chunks that reference “it”, “this method”, “as mentioned” become meaningless in isolation. Implement contextual chunking (LLM or rule-based) to make chunks self-contained.

Pitfall 4: Choosing Models by Benchmark Alone#

MTEB scores do not reflect performance on specific content. A high-benchmark model can perform poorly on domain-specific queries. Evaluate embedding models on your own test queries.

Pitfall 5: Processing in Wrong Order#

Chunking before cleaning or embedding before deduplication creates noisy results. Follow the pipeline: parse -> clean -> dedupe -> chunk -> enrich -> embed. Cleaning must keep the line breaks from parsing, because the chunker splits on them.

Practical Pipeline Setup#

The order in which you tackle data preparation matters. Here’s how to think about building your pipeline.

Start with parsing validation. Before writing any pipeline code, manually inspect parsing output for 10-20 representative documents. Look for mangled tables, missing sections, and garbled text. If your parser fails on 30% of samples, no downstream optimization will save you.

Next, establish your preprocessing baseline. Run your text through normalization, PII detection, and boilerplate removal. Compare before/after samples. The goal is clean, consistent text without losing meaningful content.

Then choose your chunking strategy based on what you learned from parsing. If your documents have clear hierarchical structure (headers, sections), leverage it with structure-aware chunking. If they’re dense technical prose, recursive splitting is your friend. If you’re dealing with mixed content types, consider routing different document types to different strategies.

Add context only after chunking works well. Contextual enrichment is powerful but adds cost and complexity. Get your basic pipeline producing reasonable results first, then measure whether contextual chunking improves your specific retrieval scenarios.

Finally, close the loop with metrics. Implement coherence and boundary quality checks. Create a small test set of queries with known relevant chunks. Run retrieval evaluations weekly as you tune parameters. Without measurement, you’re guessing.

Each step depends on the previous one working correctly, so resist the urge to implement everything at once. A simple pipeline you understand beats a complex one you cannot debug.

Validated parsing with RecursiveCharacterTextSplitter covers most corpora: it respects document boundaries, needs no extra infrastructure, and gives you a baseline to measure against. Move past it when your own numbers justify the cost. Semantic chunking pays off when recursive splits cut across topic boundaries, parent-child chunking when retrieved passages read as fragments, and contextual headers when chunks lean on pronouns that only the full document resolves. Anthropic’s figures for that last option (35% fewer top-20 retrieval failures on their own, 49% with Contextual BM25, 67% with reranking added) are the strongest case for paying for the extra LLM pass, and prompt caching keeps that pass cheap.

References#

Related posts