Chunking Legal, Insurance and Healthcare Documents

Chunk contracts, insurance policies and clinical documents along their natural structure: clauses, sections and notes.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 4 · Lesson 5 of 10 · Intermediate

Chunking Legal, Insurance and Healthcare Documents

Chunk contracts, insurance policies and clinical documents along their natural structure: clauses, sections and notes.

Generic chunkers split text by size or by headings. Legal contracts, insurance policies and clinical documents have stronger structures that carry meaning: a clause and its sub-clauses, a coverage section and its exclusions, a clinical note's sections. Splitting across those boundaries produces chunks that are misleading on their own, such as a coverage statement without the exclusion that limits it. This lesson shows how to chunk these three document families along their natural structure, with the context each chunk needs.

What you will learn

  • Why domain documents need structure-aware chunking
  • How to chunk contracts by clause numbering, keeping clause paths and definitions
  • How to chunk insurance policies so coverage, conditions and exclusions stay linked
  • How to chunk clinical documents by section, with patient-level metadata and privacy controls

Prerequisites

Principles that apply to all three

  1. Split on the document's own units: clauses, sections, notes, not character counts.
  2. Carry the path: every chunk starts with its location ("Section 4 Exclusions > 4.2 Flood").
  3. Keep qualifiers together: conditions, exceptions and definitions must not be separated from what they modify.
  4. Link related parts: store references (defined terms, cross-references, the parent section) as metadata so retrieval can bring them along.
  5. Size limits are a fallback: only split a unit further when it is too long, and then with overlap.

Legal documents: chunk by clause

Contracts number their clauses (1, 1.1, 1.1(a)). Parse the numbering into a tree and make each clause a chunk with its full path. Definitions are extracted separately so they can be added to any chunk that uses a defined term:

legal_chunker.py
import re

CLAUSE = re.compile(r"^(?P<num>\d+(?:\.\d+)*)\.?\s+(?P<title>[A-Z][^\n]{0,80})$", re.M)
DEFINITION = re.compile(r'"(?P<term>[A-Z][A-Za-z ]+)"\s+(?:means|shall mean)\s+(?P<meaning>[^.]+\.)')

def chunk_contract(text: str, doc_id: str, max_words: int = 400) -> list[dict]:
    definitions = {m["term"]: m["meaning"].strip() for m in DEFINITION.finditer(text)}
    matches = list(CLAUSE.finditer(text))
    titles: dict[str, str] = {}
    chunks = []
    for i, m in enumerate(matches):
        num, title = m["num"], m["title"].strip()
        titles[num] = title
        body = text[m.end():matches[i + 1].start() if i + 1 < len(matches) else len(text)].strip()
        parts = num.split(".")
        path = " > ".join(f"{'.'.join(parts[:j])} {titles.get('.'.join(parts[:j]), '')}".strip()
                          for j in range(1, len(parts) + 1))
        if not body:
            continue                                   # heading-only clause: its title is in the children's paths
        used_terms = [t for t in definitions if t in body]
        words = body.split()
        for start in range(0, len(words), max_words - 50):     # long clauses: windows with overlap
            piece = " ".join(words[start:start + max_words])
            chunks.append({
                "text": f"[{path}]\n{piece}",
                "metadata": {"doc_id": doc_id, "clause": num, "clause_path": path,
                             "defined_terms": used_terms},
            })
    return chunks, definitions

contract = """1. Definitions
"Confidential Information" means any non-public information disclosed by either party.
2. Obligations
2.1 Non-disclosure
The Recipient shall not disclose Confidential Information to any third party.
2.2 Exceptions
Clause 2.1 does not apply to information that becomes public through no fault of the Recipient.
"""
chunks, definitions = chunk_contract(contract, "nda-acme")
for c in chunks:
    print(c["metadata"]["clause_path"], "|", c["metadata"]["defined_terms"])
1 Definitions | ['Confidential Information']
2 Obligations > 2.1 Non-disclosure | ['Confidential Information']
2 Obligations > 2.2 Exceptions | []

At answer time, append the definitions of the terms listed in defined_terms to the context. Also store cross-references such as "Clause 2.1" (a simple regex finds them) so that retrieving 2.1 can pull in 2.2, its exception. Real contracts vary (roman numerals, lettered sub-clauses, schedules); test the clause pattern on your own documents.

Insurance policies: keep coverage and exclusions connected

A policy wording typically has definitions, insuring clauses (what is covered), conditions, exclusions, limits and endorsements. The most dangerous chunking mistake is retrieving "we will pay for water damage" without "we will not pay for flood". Two techniques help:

  • Section-type metadata: tag each chunk with section_type (coverage, exclusion, condition, limit, definition, endorsement).
  • Topic linking: give coverage and exclusion chunks about the same peril a shared topic, then retrieve the linked exclusions and conditions whenever a coverage chunk is selected.
SECTION_TYPES = {
    "coverage": re.compile(r"\b(what is covered|we will pay|insuring clause|cover)\b", re.I),
    "exclusion": re.compile(r"\b(exclusions?|what is not covered|we will not pay)\b", re.I),
    "condition": re.compile(r"\b(conditions?|you must)\b", re.I),
    "limit": re.compile(r"\b(limits?|excess|deductible|maximum)\b", re.I),
    "definition": re.compile(r"\b(definitions?|means)\b", re.I),
}
PERILS = ["fire", "flood", "water", "theft", "storm", "subsidence", "accidental damage"]

def tag_policy_section(heading: str, text: str) -> dict:
    head = heading.lower()
    section_type = next((t for t, rx in SECTION_TYPES.items() if rx.search(head)), None) \
        or next((t for t, rx in SECTION_TYPES.items() if rx.search(text[:300])), "other")
    topics = [p for p in PERILS if p in f"{head} {text.lower()}"]
    return {"section_type": section_type, "topics": topics}

def expand_with_exclusions(selected: list[dict], all_chunks: list[dict]) -> list[dict]:
    """Add exclusion and condition chunks that share a topic with any selected coverage chunk."""
    topics = {t for c in selected if c["metadata"]["section_type"] == "coverage" for t in c["metadata"]["topics"]}
    extra = [c for c in all_chunks
             if c["metadata"]["section_type"] in ("exclusion", "condition")
             and topics & set(c["metadata"]["topics"]) and c not in selected]
    return selected + extra[:4]

Also keep the policy version and effective dates on every chunk, and filter by the customer's policy version: answering from the wrong wording year is a common, costly error. Endorsements modify the base wording, so retrieve them alongside the sections they change. See Insurance Policy Document RAG for the full application.

Healthcare documents: chunk by clinical section

Clinical notes follow section conventions (for example Chief Complaint, History of Present Illness, Medications, Allergies, Assessment and Plan), and discharge summaries, lab reports and guidelines have their own. Chunk by section, keep short sections whole, and attach patient-level and encounter-level metadata:

CLINICAL_SECTIONS = ["chief complaint", "history of present illness", "past medical history", "medications",
                     "allergies", "physical exam", "assessment", "plan", "assessment and plan"]
SECTION_RE = re.compile(r"^(?P<name>" + "|".join(re.escape(s) for s in CLINICAL_SECTIONS) + r")\s*:?\s*$",
                        re.I | re.M)

def chunk_clinical_note(note: str, patient_ref: str, encounter_date: str, note_type: str) -> list[dict]:
    matches = list(SECTION_RE.finditer(note))
    chunks = []
    for i, m in enumerate(matches):
        body = note[m.end():matches[i + 1].start() if i + 1 < len(matches) else len(note)].strip()
        if not body:
            continue
        section = m["name"].title()
        chunks.append({
            "text": f"[{note_type} {encounter_date} - {section}]\n{body}",
            "metadata": {"patient_ref": patient_ref,          # a pseudonymous id, not a name
                         "encounter_date": encounter_date, "note_type": note_type, "section": section},
        })
    return chunks
  • Scope retrieval to one patient with a mandatory patient_ref filter for patient-level questions, so records never mix.
  • Keep medications and allergies whole: a list split in half can omit a critical allergy.
  • Dates matter: sort and filter by encounter date; newer results usually supersede older ones.
  • Protect health information: use pseudonymous identifiers, de-identify where possible, and follow your organisation's HIPAA or GDPR controls (GDPR- and HIPAA-Compliant RAG).

Evaluate domain chunking

Build test questions that depend on structure: "Is flood damage covered?" (needs the exclusion), "What does Clause 2.1 prohibit and are there exceptions?" (needs 2.2), "What allergies does the patient have?" (needs the whole list). Compare generic and domain chunking with the methods in Evaluating Chunking Strategies, and have a domain expert review a sample of chunks.

Key takeaways

  • Chunk domain documents along their own units: clauses, policy sections, clinical sections.
  • Prefix each chunk with its structural path and store links (definitions, cross-references, topics) as metadata.
  • Never separate coverage from its exclusions or a clause from its exceptions; expand retrieval with linked chunks.
  • For clinical text, scope retrieval to one patient, keep lists whole and protect health information.

Frequently asked questions

Can an LLM do the chunking instead of regexes?

Yes, LLM-based segmentation handles irregular documents better, at a cost per document. A common approach is rules for well-structured templates and an LLM for the rest, with spot checks.

What about scanned contracts?

Run OCR or a layout-aware parser first (Parsing Complex Documents); clause numbering is usually preserved well enough for the parser above.

Practice exercises

  1. Extend the clause pattern to lettered sub-clauses such as 2.1(a) and test it on three real contracts.
  2. Index a home-insurance wording and check that every "is X covered?" test question retrieves the matching exclusion.

Related tutorials