From PDFs to RAG: A Governed Document Ingestion Pipeline with Databricks AI Functions
A RAG system is only as useful as the documents it can understand. That sounds obvious, but document ingestion is where many enterprise search projects become complicated. PDFs have tables and page structure. DOCX files
A RAG system is only as useful as the documents it can understand.
That sounds obvious, but document ingestion is where many enterprise search projects become complicated. PDFs have tables and page structure. DOCX files contain headings and lists. HTML has navigation and markup mixed with the actual content. TXT files are simpler, but they still need consistent metadata and lineage.
Instead of building a separate pipeline for every format, we can use Databricks AI Functions to create one governed document dataset and then prepare it for retrieval.
This walkthrough focuses on four formats:
- PDF and DOCX: parse into structured document content.
- HTML and TXT: extract normalized UTF-8 text.
- All formats: store them in one Delta table.
- Search preparation: generate semantic chunks for a Databricks AI Search index.
Scope note: The SQL below is a reference implementation pattern. Validate paths, supported formats, function availability, and output schema against your workspace before using it in production.
1. The architecture
Unity Catalog Volume: /Volumes/research/raw/
|
+---------+---------+
| |
PDF / DOCX HTML / TXT
| |
ai_parse_document() UTF-8 extraction
| |
structured VARIANT normalized STRING
| |
+---------+---------+
|
research.parsed_documents
|
ai_prep_search()
|
semantic chunks
|
research.document_chunks
|
Databricks AI Search
|
retrieval for RAG apps
The important design choice is that parsing and retrieval preparation are separate stages. The first stage preserves what was found in the source document. The second stage creates chunk representations optimized for search.
2. Create the governed schema
CREATE SCHEMA IF NOT EXISTS research;
A parsed-document table can retain both representations:
CREATE TABLE IF NOT EXISTS research.parsed_documents (
document_id STRING,
source_uri STRING,
file_name STRING,
file_type STRING,
parsed_content VARIANT,
text_content STRING,
ingestion_timestamp TIMESTAMP,
source_version STRING,
processing_status STRING
)
USING DELTA;
Use one row per source document. Keep document_id stable across downstream tables, and track a source version or checksum so that changed files can be reprocessed without losing lineage.
3. Parse PDF and DOCX files
ai_parse_document() accepts binary document content and returns structured content. This is useful when page references, layout, tables, or figure descriptions matter.
INSERT INTO research.parsed_documents
SELECT
sha2(path, 256) AS document_id,
path AS source_uri,
regexp_extract(path, '[^/]+$', 0) AS file_name,
lower(regexp_extract(path, '\\.([^.]+)$', 1)) AS file_type,
ai_parse_document(content) AS parsed_content,
CAST(NULL AS STRING) AS text_content,
current_timestamp() AS ingestion_timestamp,
CAST(NULL AS STRING) AS source_version,
'PARSED' AS processing_status
FROM READ_FILES(
'/Volumes/main/research/raw/',
format => 'binaryFile'
)
WHERE lower(path) RLIKE '\\.(pdf|docx)$';
The exact volume path and file filtering should match your catalog and ingestion conventions. For large or frequently updated volumes, use an incremental ingestion mechanism rather than repeatedly scanning every file.
4. Extract HTML and TXT as text
HTML and TXT do not need the document-layout parser in this design. Read them as text and normalize the HTML before storing it.
INSERT INTO research.parsed_documents
SELECT
sha2(path, 256) AS document_id,
path AS source_uri,
regexp_extract(path, '[^/]+$', 0) AS file_name,
lower(regexp_extract(path, '\\.([^.]+)$', 1)) AS file_type,
CAST(NULL AS VARIANT) AS parsed_content,
CASE
WHEN lower(path) RLIKE '\\.html?$'
THEN trim(regexp_replace(content, '<[^>]+>', ' '))
ELSE content
END AS text_content,
current_timestamp() AS ingestion_timestamp,
CAST(NULL AS STRING) AS source_version,
'EXTRACTED' AS processing_status
FROM READ_FILES(
'/Volumes/main/research/raw/',
format => 'text'
)
WHERE lower(path) RLIKE '\\.(html?|txt)$';
The regular expression is intentionally simple. It is not a complete HTML parser: it does not reliably handle scripts, styles, entities, malformed markup, or complex page layouts. For production HTML, use a proper HTML extraction and cleanup step, then persist the normalized text.
5. Prepare both representations for search
This is where ai_prep_search() becomes useful.
It accepts either:
- A
VARIANTproduced byai_parse_document(). - A plain-text or Markdown
STRING.
It splits the document into semantic chunks and enriches chunks with document context. The output includes chunk_to_retrieve and chunk_to_embed.
Run the function on each representation and combine the prepared results:
CREATE OR REPLACE TABLE research.prepped_documents AS
SELECT
document_id,
source_uri,
ai_prep_search(parsed_content) AS search_result
FROM research.parsed_documents
WHERE parsed_content IS NOT NULL
UNION ALL
SELECT
document_id,
source_uri,
ai_prep_search(text_content) AS search_result
FROM research.parsed_documents
WHERE text_content IS NOT NULL;
The two branches avoid forcing VARIANT and STRING into a single SQL CASE expression.
6. Flatten semantic chunks into a Delta table
ai_prep_search() returns a document-level result containing a collection of chunks. Flatten that collection so that each row represents one searchable chunk.
CREATE OR REPLACE TABLE research.document_chunks AS
SELECT
chunk.value:chunk_id::STRING AS chunk_id,
prepped.document_id,
chunk.value:chunk_position::INT AS chunk_position,
chunk.value:chunk_to_retrieve::STRING AS chunk_to_retrieve,
chunk.value:chunk_to_embed::STRING AS chunk_to_embed,
chunk.value:metadata AS metadata,
prepped.source_uri,
current_timestamp() AS prepared_at
FROM research.prepped_documents AS prepped,
LATERAL variant_explode(prepped.search_result:document.contents) AS chunk;
Keep both chunk text fields:
-
chunk_to_retrieveis the content your application can return as supporting context. -
chunk_to_embedincludes additional document context to improve semantic retrieval.
Keep the source URI and document ID on every chunk. They are essential for citations, access-control filtering, debugging, and reprocessing.
7. Connect the chunk table to Databricks AI Search
The chunk table is now a suitable source for a vector-search index.
At a high level, configure the index with:
-
Primary key:
chunk_id -
Embedding source column:
chunk_to_embed -
Returned content:
chunk_to_retrieve -
Metadata:
document_id,source_uri, and extracted metadata
With a managed embedding endpoint, the index can generate embeddings from the source text. You do not necessarily need to maintain a separate hand-built embedding table.
Your application can retrieve the top relevant chunks, pass the retrieved context to an LLM or agent, and return an answer with source references.
8. Production considerations
Before calling this production-ready, address a few details:
- Incremental processing: detect new and changed files; do not reparse the entire volume on every run.
- Idempotency: use stable document identifiers and source versions to avoid duplicate chunks.
- Error handling: record parse failures, unsupported formats, and retry status.
- HTML quality: use a real HTML parser for pages with navigation, scripts, and complex markup.
- Access control: carry tenant, classification, and document ACL metadata into the chunk table and enforce authorization during retrieval.
-
Schema evolution: pin or validate the
ai_prep_searchoutput version because its result schema is versioned. - Operational checks: monitor parsing latency, token usage or inference cost, chunk counts, and index refresh status.
Also verify the current runtime and preview requirements in your Databricks workspace. ai_prep_search is documented as Beta and requires Databricks Runtime 18.2 or later under the current documentation.
9. What this design gives us
The goal is not to create the fewest tables possible. It is to keep responsibilities clear:
-
research.parsed_documentsis the governed source representation. -
research.document_chunksis the retrieval-ready representation. - Databricks AI Search is the retrieval index.
That separation makes it easier to re-chunk documents, change embedding models, audit source lineage, and rebuild the search index without parsing every source file again.
Question for the community: How are you handling mixed-format enterprise documents in your RAG pipelines? Do you preserve parsed structure alongside normalized text, or do you convert everything into plain text before chunking?
References
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.