Skip to main content

Document Ingestion Pipeline

About this documentation

Documentation of a PXL University College "AI Technology Architect" graduation project by SOFT4U BV and the project team, built as a pilot for Ziekenhuis Oost-Limburg (ZOL). Not an official ZOL publication and not endorsed by ZOL.

Before the search system can answer questions, hospital content must be transformed from its raw formats into searchable representations. The ingestion pipeline converts documents into vector embeddings for semantic search, while the entity taxonomy is seeded separately from curated taxonomy data and hub pages.

Pipeline-level trade-offs​

DecisionChosenAlternatives consideredRejected because
Embedding modelOpenAI text-embedding-3-large (1,536 dimensions, @openai2024embeddings)Self-hosted BGE-M3 (@chen2024bgem3) at 1,024 dimensions; OpenAI text-embedding-3-small (cheaper)BGE-M3 was the previous baseline. The migration (ADR-0048) accepted a cost of roughly $0.20 per month for stronger Dutch retrieval (MTEB-NL about 64.6 versus 60.0) and removal of the self-hosting dependency. The smaller OpenAI model was rejected because the retrieval gap on Dutch medical content, about 3 MTEB-NL points, was small but measurable.
Chunking strategyMarkdown-header-aware split with a 350-token target, 70-token overlap and a hard 450-token ceilingFixed-token sliding window; recursive character-based splitting; semantic-similarity-based chunkingHospital content (brochures, condition pages) is inherently sectioned. A fixed window severs section boundaries and dilutes the semantic signal; semantic chunking adds a model call per document that is not justified at this corpus size. Header-aware splitting respects existing structure at negligible cost.
PDF isolationPDFs are processed in a separate worker process with a 120-second timeout and image-only detectionIn-process extraction; an external extraction serviceA misbehaving PDF processed in-process can exhaust memory, crash or hang the server; both were observed during the initial import of the brochure collection (about 1,000 brochures, according to the January 2026 project brief). An external service adds operational surface. A separate worker process loses only the worker on a bad PDF and lets the next URL through.
Re-ingestion strategyContent-hash-based incremental updatePeriodic full re-crawl; checking last-modified headersA full re-crawl is prohibitively slow; last-modified headers are rarely populated correctly by the hospital's content management system. A content-hash comparison captures actual changes (see Incremental updates below).

Pipeline overview​

Step 1: Content extraction​

The extraction layer normalises diverse document formats into a common Markdown representation:

Source formatExtraction toolNotes
PDFPyMuPDFIsolated worker process with a 120-second timeout
DOCXpython-docxPreserves heading structure
HTMLcrawl4aiAsynchronous crawling with JavaScript rendering
SitemapCustom parserDiscovers URLs for the crawler

Isolated PDF extraction​

PDF extraction runs in a separate worker process rather than in the main server process. This protects the ingestion pipeline from problematic PDFs that could crash, hang or consume excessive memory:

  • 120-second timeout: each extraction has a hard timeout. If a PDF takes longer (for example a 200-page scanned brochure), the worker is stopped and the document is marked as failed.
  • Image-only detection: the first pages are inspected for extractable text. A PDF containing only scanned images with no text layer (common for older brochures) is classified as image-only and skipped with a descriptive error rather than producing empty chunks.
  • Process isolation: a crash or memory leak in the PDF library affects only the worker, not the server.

Sitemap-driven crawling is important for the pilot hospital: its public website exposes a comprehensive sitemap, which the crawler uses to discover and ingest all public-facing content systematically.

The extracted Markdown is stored in object storage (MinIO) as the canonical source, so content can be re-processed without re-crawling when the chunking or embedding strategy changes.

Step 2: Text chunking​

Chunking splits documents into segments suitable for embedding. The strategy strongly affects retrieval quality: chunks that are too large dilute the semantic signal, chunks that are too small lose context.

Chunking configuration​

ParameterValueRationale
Target size350 tokensEmpirically tested for the embedding model; unchanged from the earlier baseline at the embedding migration
Maximum size450 tokensHard ceiling to prevent oversized chunks
Overlap70 tokensPreserves context across chunk boundaries
TokenizerOpenAI-family tokenizerExact token counts for the embedding model
Split awarenessMarkdown headersRespects document structure
Why Markdown-aware splitting?

Hospital content is inherently structured. A brochure about knee surgery has sections such as "Voorbereiding" (preparation), "Procedure" and "Nazorg" (aftercare). Splitting at heading boundaries means each chunk represents a coherent topic rather than an arbitrary slice of text. This decision is documented in ADR-0001.

Metadata attachment​

Each chunk carries metadata that enables downstream filtering and boosting:

  • Source URL and source title of the original page or document
  • Section headers: the Markdown heading hierarchy above the chunk
  • Category: inferred from the source, normalised to title case
  • Ingestion timestamp, for recency-based boosting
  • Canonical questions: one or two Dutch questions the chunk answers (Step 7)

The earlier separate title-keyword field was replaced by keyword search that includes the document title directly (ADR-007).

Category normalisation​

Categories are normalised to title case during ingestion. This prevents silent failures of the metadata boost that would otherwise occur when the casing of an ingested category differed from the intent-to-category mapping used at query time.

Step 3: PII detection​

The PII detection layer scans content for personally identifiable information using pattern matching. It looks for email addresses, phone numbers and national-number-style digit patterns, and logs each detection.

Intentional design choice

PII masking is disabled for the hospital's content. Hospital contact information (email addresses, phone numbers) is intentionally public, because patients need it to book appointments and reach departments. The detector still logs detections for audit purposes but does not redact content. See PII Protection for the rationale.

Step 4: Embedding generation​

Each chunk is converted into a 1,536-dimensional dense vector using OpenAI text-embedding-3-large (see ADR-0048, @openai2024embeddings; the dense retrieval pattern follows @karpukhin2020dpr):

  • Dimensions: 1,536, truncated from the model's native 3,072 to fit the 2,000-dimension limit of the pgvector HNSW index (@pgvector_docs)
  • Language support: strong multilingual performance; MTEB-NL retrieval about 64.6, above the earlier model's 60.0
  • Cost: about $0.13 per million tokens; roughly $0.20 per month at 25,000 queries per month (an estimate using the query volume stated in the January 2026 project brief)
  • Batching: all texts of a document are sent in one batch call

The earlier self-hosted model remains available as a configurable fallback and for a re-ranking experiment.

Step 5: Vector storage​

Embedded chunks are stored in PostgreSQL with the pgvector extension. Each record holds the chunk text, its embedding vector and its metadata. An HNSW index enables approximate nearest-neighbour search at query time.

Step 6: Keyword search index​

After chunks are stored, each receives a PostgreSQL full-text search vector for BM25-style keyword search (see ADR-007). The vector is built from the parent document's title plus the chunk content. Only chunks not yet indexed are processed, which makes the step idempotent for incremental ingestion.

Key design choices:

  • No language-specific stemming: Dutch medical terms such as "cardioversie" and "orthopedie" should match exactly rather than be reduced to stems.
  • Title included: title terms are searchable through keyword search.
  • Inverted index: a GIN index gives sub-millisecond keyword lookup.

Step 7: Canonical question generation​

Conceptual overview

For the reasoning behind canonical questions and page summaries (hypothetical-question indexing and contextual retrieval, and how both steer query-time retrieval) see Ingestion Enrichment. This section documents the procedure.

After the keyword index is built, the pipeline asks the standard-tier language model to generate one or two Dutch questions per chunk, with an instruction to return only questions that the text answers. When contextual embeddings are enabled this happens synchronously before embedding, with concurrent calls; otherwise it runs as a background task.

Example: a chunk about visiting hours yields a question such as "Wat zijn de bezoekuren op cardiologie?"; a chunk describing an orthopaedic surgeon yields "Wie is de orthopedisch chirurg?".

The questions are stored in the chunk's metadata and appended to the keyword index, so keyword search matches both content and canonical questions. This improves keyword recall for question-phrased queries, which are the most common user input.

Step 8: Page summary generation​

During entity extraction, the language model generates a page summary for every page: a two-to-three-sentence Dutch description of what the page covers. The summary is stored with the chunk metadata and prepended to the first chunk of each document during context assembly, implementing the contextual retrieval pattern.

Summaries are generated for all pages, not just hub pages

Non-hub pages do not write entities to the taxonomy, but a summary is still generated for every document so all chunks benefit from contextual retrieval at query time. See ADR-0014.

Enrichment retry and gap detection​

Enrichment steps (canonical questions, page summaries, entity extraction) can fail for individual documents because of transient API errors, rate limits or timeouts. Rather than re-running the whole pipeline, the system detects and backfills gaps inline:

  1. Gap detection: before enrichment, the pipeline finds documents that completed chunking but lack enrichment artefacts.
  2. Selective backfill: only the missing steps are re-executed; extraction and chunking are skipped.
  3. Retry integration: backfill is part of the normal ingestion flow, so operators need no separate retry action.

Language-model rate limiting​

To stay within provider rate limits and control cost, enrichment enforces a short pause (200 ms) between consecutive language-model calls. This simple throttle prevents "too many requests" errors during large batch runs.

Taxonomy seeding (separate from ingestion)​

The entity taxonomy in PostgreSQL is not populated during regular page ingestion. It is seeded from two curated sources in a separate process:

Why separate taxonomy seeding?​

The taxonomy needs high-quality, validated data to support structured lookups such as "which doctors work in cardiology?". Letting every crawled page write entities caused quality problems early in development:

  • Cross-product relationships: departments linked to all campuses instead of the correct one
  • Garbage entity names: body parts and job titles parsed as doctor names
  • Scope leakage: conditions associated with departments that do not treat them

The solution was to restrict taxonomy writes to two curated sources:

  1. Frozen taxonomy: a manually curated single source of truth for departments, conditions, treatments, examinations, campus mappings and their relationships. It encodes institutional knowledge, such as which department is located on which campus and which conditions it handles.
  2. Hub pages: structural listing pages (classified as hubs by a language-model binary classifier) that contain validated doctor, department and specialty information. Only these pages may write to the taxonomy; this restriction is on by default. An earlier eight-type page classification was replaced by this binary hub/detail classifier.

This architecture is documented in ADR-0028.

What happens during regular page ingestion?​

With the hub-only restriction on (the default), ingestion still runs entity extraction and validation on every page, but only to generate page summaries; no entities are written to the taxonomy. The flow:

  1. Rule-based extraction identifies entities and relationships.
  2. Language-model validation generates a page summary.
  3. The summary is stored with the chunk metadata.
  4. Taxonomy storage is skipped; entities are discarded and only the summary is kept.
  5. Entity types are denormalised into the document metadata for search boosting.

Entity-type and campus denormalisation​

After extraction, the entity types and campus names found in a document are copied onto the document's metadata (for example the entity types "doctors", "departments", "conditions", and the campuses referenced). This lets the metadata boosting stage apply entity-type and campus boosts without runtime graph lookups, keeping boosting latency under 5 ms.

URL crawling and orchestration​

Before content is processed, URLs must be discovered, classified and managed. The crawl-to-ingest pipeline uses persistent records for this.

Crawl sessions​

A crawl session is a sitemap crawl that discovers URLs. The crawler parses the hospital's sitemap, classifies each URL by type (HTML, PDF, DOCX or ignored) and stores it with a status that moves from discovered to indexed, failed or skipped.

Ingestion jobs​

An ingestion job is a batch operation over discovered URLs; each URL gets its own result record for granular tracking. The orchestration layer provides:

FeatureApproachPurpose
Concurrent processing10 asynchronous workers over batches of 50Throughput without overwhelming external services
Live progressProgress state in Redis streamed to the administration UIReal-time updates (current URL, chunk counts, entity names)
Job cancellationA cancel flag checked before each batchGraceful stop without stopping the server
Content de-duplicationTitle-based duplicate checkThe hospital site serves some content under several URL paths
Fault toleranceA rescue step for stuck resultsIf error recording fails, the result is still forced to "failed"
Per-URL timeout5 minutes per URLA single slow URL cannot block the batch
Document timeout120 seconds per documentRaises an error instead of silently accepting a zero-chunk result
Loop guardMaximum iterations on the batch loopPrevents endless re-fetching if results stay "pending"
Non-critical progress storeAll progress-reporting calls tolerate failureLive details are a convenience and never crash processing

URL type classification​

URL typePatternExtraction method
HTML.html or no extensioncrawl4ai (JavaScript rendering) with a plain HTTP fallback
PDF.pdfPyMuPDF text extraction
DOCX.docxpython-docx (paragraphs and tables)
Ignoredimages, stylesheets, scriptsSkipped (not content)

Scheduled ingestion​

The pipeline can run nightly under operator-controlled gating. A scheduler triggers it at 03:00 UTC, and an operational mode setting decides what happens:

ModeBehaviour
OffSkip both crawl and ingest. Used during incident response or while a long manual ingestion is running.
ManualThe crawl runs (sitemap discovery and URL classification) but ingestion halts. Administrators drive ingestion through the pipeline wizard in the administration UI.
AutoThe full pipeline (fetch, chunk, embed, delete handling) runs nightly. This mode went live on the pilot on 2026-04-22; an operator can change the mode at any time without a deployment.

Audit trail​

Every nightly invocation, whatever the mode, writes one audit record per hospital covering: start and end time, the active mode, counts of URLs discovered, indexed, failed and skipped, a coarse failure class for alerting (for example "empty content" or "sitemap timeout") and free-text notes such as the most frequent failing URLs.

Disarming automatic ingestion without a deployment​

An operator can switch the mode to "manual" in the server configuration and restart the application; the next nightly cycle respects the new mode.

Incremental updates​

The pipeline supports incremental ingestion, an established practice in web-crawling literature. Olston and Najork (2010) identify three strategies for keeping a crawl fresh: periodic re-crawling, change-driven selective updates and frequency-based scheduling. Cho and Garcia-Molina (2000) showed that incremental crawlers that selectively update their index achieve higher "freshness" (the fraction of the collection that is up to date) than batch refreshes.

The system uses content-hash-based change detection, which Cho and Garcia-Molina (2003) report can improve crawl efficiency by focusing effort on content that actually changed:

  1. New documents: crawl the sitemap, identify new URLs, ingest only the new content.
  2. Updated documents: compare SHA-256 content hashes and re-ingest only changed documents, following the hash-based approach discussed by Olston and Najork (2010, section 4.2).
  3. Deleted documents: mark chunks inactive (soft delete, preserving provenance and an audit trail).
  4. Re-processing: an administrative reset returns URL status to discovered without re-crawling, so content can be re-processed under a new chunking or embedding strategy.

This avoids full re-ingestion, which would be prohibitively slow for a corpus of about 1,000 brochures (January 2026 project brief) plus hundreds of web pages.

Academic foundation