1. The Spring AI ETL Pipeline Architecture
Document domain object:-
The
DocumentModel: Every piece of ingested content is represented as aDocumentinstance containing:-
ID: A unique identifier (UUID) for tracking and idempotent updates.
-
Content (
text): The textual payload to be embedded and retrieved. -
Metadata (
Map<String, Object>): Key-value attributes (such as source filename, page number, creation timestamp, or extracted keywords) used for filtering and citations. -
Media (Optional): Binary/multimodal attachments when processing non-text assets.
-
-
Three-Stage Flow:
-
Extract (
DocumentReader): ImplementsSupplier<List<Document>>to pull raw data from external files, APIs, or web pages intoDocumentobjects. -
Transform (
DocumentTransformer): ImplementsFunction<List<Document>, List<Document>>to clean, split, summarize, or enrich documents. Multiple transformers can be chained sequentially. -
Load (
DocumentWriter): ImplementsConsumer<List<Document>>to persist processed documents into aVectorStore(generating embeddings automatically) or export them to files.
-
2. Document Loading (DocumentReader)
DocumentReader implementations tailored to common enterprise file formats:| Document Reader | Supported Formats | Key Behavior & Capabilities |
TextReader |
Plain text (.txt, .log, source code) |
Reads raw character streams into a single Document and attaches basic resource metadata (charset, source URI). |
JsonReader |
JSON files & API payloads | Parses JSON arrays or objects; allows specifying target JSON keys for text extraction and custom JsonMetadataGenerator logic. |
MarkdownDocumentReader |
Markdown (.md) |
Parses structural Markdown elements—separating horizontal rules, headings, code blocks, and blockquotes into distinct, context-preserving Document chunks. |
PagePdfDocumentReader |
PDF documents | Uses Apache PDFBox to extract text page-by-page, attaching page numbers and document properties as metadata. |
ParagraphPdfDocumentReader |
Structured PDFs with a Table of Contents | Uses PDF catalog/bookmark outlines to split PDFs along logical chapter and paragraph boundaries rather than arbitrary page breaks. |
JsoupDocumentReader |
HTML files & web pages | Extracts clean text from DOM elements using CSS selectors, stripping navigation bars, scripts, and boilerplate HTML tags. |
TikaDocumentReader |
Word (.docx), PowerPoint (.pptx), Excel (.xlsx), EPUB, RTF |
Powered by Apache Tika, acting as a universal reader capable of extracting text and metadata across dozens of proprietary office formats. |
3. Document Transformation & Chunking (TextSplitter)
Core Chunking Strategies in Spring AI
-
TokenTextSplitter: The primary recursive text splitter in Spring AI. Rather than splitting blindly by character count, it splits text based on actual LLM token counts (usingjtokkit/ cl100k_base encoding) while respecting natural boundaries such as sentence endings (.,?,!) and paragraph breaks.-
Key Tuning Parameters:
-
chunkSize: Target token count per chunk (commonly 500–800 tokens). -
minChunkSizeChars&minChunkLengthToEmbed: Prevents tiny, meaningless trailing fragments from being indexed. -
maxNumChunks: Caps total chunks per document to protect against runaway files. -
keepSeparator: Retains punctuation/newlines so sentence grammar stays intact.
-
-
-
Chunk Overlap: Adjacent chunks share a sliding window of overlapping tokens (typically 10%–20% of chunk size) so sentences or ideas spanning a split boundary are not severed.
-
Structural Splitting: Format-specific readers like
MarkdownDocumentReaderandParagraphPdfDocumentReaderperform semantic pre-chunking based on headings and sections before token-level splitting is applied. -
Content Formatting (
ContentFormatter): Controls how metadata keys and text content are merged or excluded when generating the final embedding string versus what is shown to the LLM.
4. Metadata Extraction & Enrichment
"department": "engineering" created in 2026) and accurate source attribution.Two Tiers of Metadata Extraction
-
Structural & Provenance Metadata (Rule-Based):
-
Automatically populated by
DocumentReaderimplementations during ingestion: source filename, file path/URL, page number, section heading, last-modified timestamp, and ingestion batch ID. -
Custom business metadata (such as
tenantId,accessRole, ordocumentCategory) is injected programmatically prior to writing.
-
-
AI-Powered Metadata Enrichment (
DocumentTransformer): Spring AI includes LLM-backed transformers that analyze each chunk during ingestion and automatically generate high-value semantic metadata:-
KeywordMetadataEnricher: Uses aChatModelto extract the top $N$ domain-specific keywords/entities from each chunk and stores them in theexcerpt_keywordsmetadata field. -
SummaryMetadataEnricher: Uses aChatModelto generate concise summaries of the current chunk, as well as the previous and next adjacent chunks (section_summary,prev_section_summary,next_section_summary). Storing neighbor summaries inside metadata solves the “lost context” problem when isolated chunks are retrieved during RAG.
-
5. Production Best Practices
-
Propagate Parent Metadata to All Chunks: Spring AI’s
TextSplitterautomatically copies parentDocumentmetadata onto every child chunk—always attach tenant IDs, security ACL tags, and source filenames before splitting. -
Balance Chunk Size with Retrieval Granularity: Smaller chunks (256–512 tokens) yield sharper semantic matches for factoid lookups, while larger chunks (800–1,200 tokens) provide richer surrounding context for complex synthesis tasks.
-
Use AI Enrichers Selectively: Because
KeywordMetadataEnricherandSummaryMetadataEnricherinvoke an LLM for every chunk, run them with fast, low-cost models (such as Gemini Flash, Claude Haiku, or local Ollama models) during offline batch ingestion to control latency and token spend. -
Clean Noisy Text Before Embedding: Strip headers, footers, page watermarks, and boilerplate navigation blocks during the transformation stage so vector embeddings reflect core subject matter rather than repetitive formatting noise.
Hands-on Experiment: Build a Smart Document Processing Application with Spring AI
Aim: To load documents, split them into chunks, extract metadata with Spring AI, and store the results in MySQL.
Description: Before documents can be searched by an AI, they must be read, cleaned and split into manageable pieces. Spring AI’s document ETL pipeline uses readers for sources like PDF, text and Word files, transformers that split content into chunks, and writers that store the results. Chunking keeps each piece within model limits, and metadata such as source and page number is attached to each chunk. It is used to prepare enterprise documents for embedding, retrieval and accurate citation.
Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE, Postman
Steps:
- Generate the project with Spring Initializr
- Add the Spring AI Tika document reader dependency
- Configure MySQL and file upload limits
- Create the
ProcessedDocumentandDocumentChunkentities and repositories - Create the service that runs the load, chunk, metadata and save pipeline
- Create the REST controller
- Run the application
- Test with Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven, Language: Java
- Spring Boot: 3.5.x (Spring AI 1.1 needs 3.5.x, not 3.3.x)
- Group:
com.example, Artifact:smart-document-processing - Packaging: Jar, Java 17
- Dependencies: Spring Web, Spring Data JPA, MySQL Driver. The Tika reader is added manually in
pom.xml.
Step 2: Project Structure
smart-document-processing
├── pom.xml
└── src/main
├── java/com/example/docprocessing
│ ├── SmartDocumentProcessingApplication.java
│ ├── entity
│ │ ├── ProcessedDocument.java
│ │ └── DocumentChunk.java
│ ├── repository
│ │ ├── ProcessedDocumentRepository.java
│ │ └── DocumentChunkRepository.java
│ ├── service/DocumentProcessingService.java
│ └── controller/DocumentController.java
└── resources/application.properties
Step 3: Github Link:
Step 4: Download the application from above github link, then test the below CURD operations
POST Payloads and URLs (Postman)
1. Process plain text (JSON)POST http://localhost:8080/api/documents/text?chunkSize=60
{
"fileName": "remote-work-policy.txt",
"content": "Remote Work Policy. Employees may work remotely up to three days a week with manager approval. Remote employees must use the corporate VPN and enable multi-factor authentication for every login. Company laptops must be encrypted and updated every month. Confidential documents must never be stored on personal devices. Employees are expected to be available during core hours from ten in the morning to four in the afternoon. Team meetings are held on video and cameras should be on for discussions. Travel and internet expenses are reimbursed only when approved in advance by the department head. Violations of the security rules can lead to disciplinary action and withdrawal of remote work privileges."
}
2. Upload a real file (PDF, DOCX, TXT)POST http://localhost:8080/api/documents/upload?chunkSize=100
In Postman, choose Body → form-data, set the key file to type File, and select your document.
3. View the results (GET)
http://localhost:8080/api/documentslists all processed documentshttp://localhost:8080/api/documents/1shows the document metadatahttp://localhost:8080/api/documents/1/chunksshows each chunk with its word count, keywords and metadata
4. Delete
DELETE http://localhost:8080/api/documents/1
Try the same text with chunkSize=30 and then chunkSize=200. Smaller sizes give more chunks, which is the main tuning decision when you prepare documents for a vector store.
