Loading and Cleaning Documents Before You Index Them

JS
Jai Singh
11 Nov, 2026 4 min read 14 views

Clean input is the cheapest way to improve a RAG system. Retrieval can only find what you indexed, and noisy text such as menus, cookie banners and repeated footers wastes space, dilutes embeddings and pollutes answers. Before you split anything, extract plain text, strip boilerplate, keep metadata and remove duplicates.

Step 1: extract text, keep structure

Different sources need different extraction. Plain text and Markdown files can be read directly. HTML needs a parser that drops scripts, styles and navigation. PDFs need a PDF text extractor, and scanned PDFs need OCR. We cover PDFs and tables in a later post.

Where possible keep structure: headings, list markers and paragraph breaks. Structure helps chunking later, because you can split on headings instead of guessing.

Step 2: strip boilerplate from HTML

The example uses BeautifulSoup (pip install beautifulsoup4). It removes tags that rarely contain content, then converts the rest to text with line breaks preserved.

from bs4 import BeautifulSoup

def html_to_text(html: str) -> str:
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup(["script", "style", "nav", "footer", "header", "aside", "form"]):
        tag.decompose()
    main = soup.find("main") or soup.find("article") or soup.body or soup
    text = main.get_text(separator="\n")
    return text

sample = """
<html><body>
  <nav>Home | Pricing | Login</nav>
  <main><h1>Refund policy</h1><p>You can request a refund within 30 days.</p></main>
  <footer>Copyright 2025 Example Corp</footer>
</body></html>
"""
print(html_to_text(sample))

The output contains only the heading and the policy sentence. The navigation and footer are gone. If you indexed them, every page would carry the same "Home | Pricing | Login" text, and those repeated words would make unrelated pages look similar.

Step 3: normalize the text

After extraction, tidy whitespace and characters. Keep this step small and predictable.

import re
import unicodedata

def normalize(text: str) -> str:
    text = unicodedata.normalize("NFKC", text)
    text = text.replace("\u00a0", " ")          # non-breaking space
    text = re.sub(r"[ \t]+", " ", text)         # collapse spaces
    text = re.sub(r"\n{3,}", "\n\n", text)      # at most one blank line
    return text.strip()

Do not over-clean. Removing punctuation or lowercasing everything is usually unnecessary for embedding models and can remove meaning, for example in code and identifiers.

Step 4: keep metadata

Store facts about each document alongside its text: a stable ID, the source URL or file path, the title, the author, the last-modified date, the language, and any access group. You will use these for filtering, for citations and for refreshing the index. Adding metadata later is painful, so capture it while you load.

from dataclasses import dataclass, field
import hashlib

@dataclass
class Document:
    id: str
    text: str
    source: str
    title: str = ""
    modified: str = ""
    meta: dict = field(default_factory=dict)

def make_document(path: str, text: str, title: str, modified: str) -> Document:
    doc_id = hashlib.sha256(path.encode("utf-8")).hexdigest()[:16]
    return Document(id=doc_id, text=normalize(text), source=path,
                    title=title, modified=modified)

The ID is derived from the path, so the same file always gets the same ID. This makes updates and deletions possible later.

Step 5: remove duplicates

Duplicate content wastes money and crowds the top results with copies of the same passage. Exact duplicates are easy to catch with a hash of the normalized text. Near duplicates, such as the same page under two URLs with a different date, need fuzzier methods, but exact hashing already removes much of the problem.

import hashlib

def dedupe(docs):
    seen = set()
    unique = []
    for d in docs:
        key = hashlib.sha256(d.text.encode("utf-8")).hexdigest()
        if key not in seen:
            seen.add(key)
            unique.append(d)
    return unique

Special cases worth handling

Some content needs extra care. Tables flattened into text can lose their row and column meaning, so convert them to a readable form such as one sentence per row, or keep them as Markdown. Code blocks should be kept intact and labelled with their language. Emails and chat logs contain quoted replies and signatures that repeat in every message, so strip quoted text, otherwise one message appears in dozens of chunks.

Documents with revision history, such as wiki pages, should be loaded in their latest version only unless history is the point. Old versions create contradictory chunks, and the model may quote an outdated rule. Likewise, mark drafts and archived pages in metadata so you can filter them out at query time, or skip them entirely during loading.

Finally, log what you load. Record how many documents each source produced and how many were dropped as empty or duplicate. A sudden drop in the count tells you that a scraper broke or a folder moved, long before users notice missing answers.

Checklist before indexing

  • Open ten random documents after extraction and read them. Do they look like what a person would read?
  • Search the extracted text for strings like "Accept cookies" or "Skip to content". If you find them, strip them.
  • Check that tables and lists did not collapse into one unreadable line.
  • Confirm that every document has an ID, a source and a modified date.
  • Check that text from non-English pages kept its accents and characters.
  • Remove empty or near-empty documents, which only create noise.

Time spent here is repaid in every later stage. If retrieval returns strange results, inspect the stored chunk text first. Often the cause is junk that cleaning would have removed.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.