Document Loading, Transformation, Chunking and Metadata Extraction

In Spring AI, Document Loading, Transformation, Chunking, and Metadata Extraction form the ETL (Extract, Transform, Load) Pipeline. Before a Large Language Model (LLM) or Vector Database can answer questions over private enterprise knowledge, raw unstructured files must be ingested, split into semantically meaningful pieces, enriched with searchable metadata, and persisted as vector embeddings.

1. The Spring AI ETL Pipeline Architecture

Spring AI models data ingestion around three standardized Java functional interfaces built on top of a unified Document domain object:
  • The Document Model: Every piece of ingested content is represented as a Document instance 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:

    1. Extract (DocumentReader): Implements Supplier<List<Document>> to pull raw data from external files, APIs, or web pages into Document objects.

    2. Transform (DocumentTransformer): Implements Function<List<Document>, List<Document>> to clean, split, summarize, or enrich documents. Multiple transformers can be chained sequentially.

    3. Load (DocumentWriter): Implements Consumer<List<Document>> to persist processed documents into a VectorStore (generating embeddings automatically) or export them to files.

2. Document Loading (DocumentReader)

Spring AI provides a rich suite of built-in 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)

Embedding models have strict context limits (e.g., 512 to 8,192 tokens), and embedding an entire 100-page manual into a single vector dilutes semantic accuracy. Chunking divides large documents into focused, retrieval-sized segments while preserving semantic continuity.

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 (using jtokkit / 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 MarkdownDocumentReader and ParagraphPdfDocumentReader perform 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

Metadata transforms a vector store from a flat similarity index into a precision enterprise search engine, enabling hybrid filtering (e.g., searching only documents from "department": "engineering" created in 2026) and accurate source attribution.

Two Tiers of Metadata Extraction

  1. Structural & Provenance Metadata (Rule-Based):

    • Automatically populated by DocumentReader implementations 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, or documentCategory) is injected programmatically prior to writing.

  2. 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 a ChatModel to extract the top $N$ domain-specific keywords/entities from each chunk and stores them in the excerpt_keywords metadata field.

    • SummaryMetadataEnricher: Uses a ChatModel to 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 TextSplitter automatically copies parent Document metadata 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 KeywordMetadataEnricher and SummaryMetadataEnricher invoke 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:

  1. Generate the project with Spring Initializr
  2. Add the Spring AI Tika document reader dependency
  3. Configure MySQL and file upload limits
  4. Create the ProcessedDocument and DocumentChunk entities and repositories
  5. Create the service that runs the load, chunk, metadata and save pipeline
  6. Create the REST controller
  7. Run the application
  8. 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

json
{
  "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/documents lists all processed documents
  • http://localhost:8080/api/documents/1 shows the document metadata
  • http://localhost:8080/api/documents/1/chunks shows 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.

Scroll to Top