Spring › Spring-AI

Building a RAG document ETL pipeline with TokenTextSplitter

Parse PDF and Markdown files with Spring AI 2.0.1 DocumentReader, TokenTextSplitter, a custom ChunkOverlapTransformer, and metadata enrichment.

Building a RAG document ETL pipeline with TokenTextSplitter

When teams build RAG systems, they spend weeks debating models and vector databases, yet most retrieval quality problems trace back to how documents are parsed, chunked, and tagged during ingestion. This post walks through building a Spring AI 2.0.1 document ETL pipeline with DocumentReader, TokenTextSplitter, a sentence-aware ChunkOverlapTransformer, and business metadata enrichment.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, and Java 25. Source code lives in the spring-ai-examples (rag-etl) module.


How the Spring AI document ETL pipeline flows

Spring AI models document ingestion around three functional interfaces—DocumentReader (Extract), DocumentTransformer (Transform), and DocumentWriter (Load). Keeping each stage small and composable lets you test chunking and metadata logic without spinning up a vector database or paying for embedding API calls.

flowchart TD
    File["Source Document (PDF / Markdown / TXT)"] --> Reader["1. DocumentReader (Extract)"]
    Reader --> Splitter["2. TokenTextSplitter (Token Chunking)"]
    Splitter --> Overlap["3. ChunkOverlapTransformer (Sentence Overlap)"]
    Overlap --> Enricher["4. SourceMetadataEnricher (Department / Author)"]
    Enricher --> Chunks["5. Enriched Chunks (DTO / VectorStore)"]
  1. Extract (DocumentReader): Pulls raw text and structural metadata (file name, page number) from binary files into Document instances.
  2. Token chunking (TokenTextSplitter): Splits documents by tokenizer count (chunkSize) so every chunk fits comfortably inside your embedding model’s context window.
  3. Context preservation (ChunkOverlapTransformer): Carries the trailing 1–2 complete sentences from chunk N-1 into the head of chunk N so boundary facts aren’t lost.
  4. Metadata enrichment (SourceMetadataEnricher): Attaches access-control and audit fields (department, author, chunk_index, ingested_at) needed later for vector-store filtering.

Choosing a chunking strategy and when not to chunk

StrategyHow it splitsBest forMain weakness
Fixed character lengthString.length slicesQuick ASCII prototypesBreaks multi-byte characters and ignores token limits
Token-based (TokenTextSplitter)Tokenizer budget + punctuation hintGeneral PDFs, handbooks, mixed-language docsNo built-in overlap in Spring AI 2.0.1
Markdown / heading-basedStructural headers (#, ##)Clean technical docs and wikisOversized sections still exceed embedding limits
No chunking (full context)Send whole file as-isStatic docs under ~50k–100k tokens queried repeatedlyHigh per-request cost without Gemini Context Caching

When not to build a chunking ETL pipeline: If your knowledge base is a single 40-page handbook that changes once a quarter, splitting it into chunks and managing a vector store adds unnecessary failure modes. Passing the full document with server-side context caching often yields higher accuracy with far less code.


Project setup and dependencies

Add spring-ai-pdf-document-reader (backed by Apache PDFBox) and spring-ai-markdown-document-reader alongside the Spring AI starter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
plugins {
    kotlin("jvm") version "2.3.21"
    kotlin("plugin.spring") version "2.3.21"
    id("org.springframework.boot") version "4.1.1"
    id("io.spring.dependency-management") version "1.1.7"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("org.springframework.ai:spring-ai-pdf-document-reader")
    implementation("org.springframework.ai:spring-ai-markdown-document-reader")
    implementation("tools.jackson.module:jackson-module-kotlin")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
}

Selecting a DocumentReader by file extension

Dispatch uploaded files to the appropriate reader based on extension so the rest of the pipeline only sees List<Document>:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fun readDocuments(file: MultipartFile): List<Document> {
    val filename = file.originalFilename ?: "document.txt"
    val resource = ByteArrayResource(file.bytes)

    return when {
        filename.endsWith(".pdf", ignoreCase = true) -> {
            PagePdfDocumentReader(resource, PdfDocumentReaderConfig.builder().build()).read()
        }
        filename.endsWith(".md", ignoreCase = true) -> {
            MarkdownDocumentReader(resource, MarkdownDocumentReaderConfig.builder().build()).read()
        }
        else -> {
            TextReader(resource).apply { customMetadata["file_name"] = filename }.read()
        }
    }
}

PagePdfDocumentReader emits one Document per PDF page and automatically populates page_number in its metadata map. Preserving that field early is what lets your RAG endpoint cite exact page numbers when answering user questions later.


TokenTextSplitter and sentence-aware overlap

Why token splitting beats character splitting

Splitting on String.length works poorly as soon as documents mix English with CJK or Korean text. One English word averages ~1.3 tokens, whereas a single Korean syllable can take 2–3 tokens depending on the tokenizer. TokenTextSplitter uses an actual tokenizer (JTokkit / cl100k_base by default) to enforce consistent token budgets:

1
2
3
4
5
val splitter = TokenTextSplitter.builder()
    .withChunkSize(chunkSize)             // Default: 800 tokens
    .withMinChunkSizeChars(350)           // Minimum char length before cutting at punctuation
    .withKeepSeparator(true)
    .build()

Working around the missing chunkOverlap in Spring AI 2.0.1

Spring AI 2.0.1 TokenTextSplitter limitation: Unlike LangChain’s splitters, Spring AI 2.0.1’s TokenTextSplitter doesn’t expose a chunkOverlap parameter. Worse, when a chunk hits the token ceiling mid-sentence or mid-word in multi-byte scripts (splitting a word across chunk 0 and chunk 1), both chunks produce degraded embeddings and drop the connecting context.

To fix this without replacing TokenTextSplitter, I chain a custom DocumentTransformer right after it. ChunkOverlapTransformer extracts the last one or two complete sentences from the previous chunk (capped by a token budget) and prepends them to the next chunk:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package io.github.cmsong111.rag_etl.etl

import org.springframework.ai.document.Document
import org.springframework.ai.document.DocumentTransformer

class ChunkOverlapTransformer(
    private val overlapTokenBudget: Int = 50
) : DocumentTransformer {

    override fun apply(documents: List<Document>): List<Document> {
        if (overlapTokenBudget <= 0 || documents.size <= 1) return documents

        val enriched = mutableListOf<Document>()
        var previousTrailingSentences = ""

        for ((index, doc) in documents.withIndex()) {
            val text = doc.text ?: ""
            val newText = if (index > 0 && previousTrailingSentences.isNotBlank()) {
                "$previousTrailingSentences\n\n$text"
            } else {
                text
            }

            enriched += Document(
                doc.id,
                newText,
                HashMap(doc.metadata).apply { put("has_overlap", index > 0) }
            )

            // Extract the last 1-2 sentences of the current chunk for the next chunk
            previousTrailingSentences = extractTrailingSentences(text, overlapTokenBudget)
        }
        return enriched
    }

    private fun extractTrailingSentences(text: String, budget: Int): String {
        val sentences = text.split(Regex("(?<=[.?!\\n])\\s+"))
        return sentences.takeLast(2).joinToString(" ").take(budget * 4)
    }
}

Debug log comparing chunks with sentence-level overlap enabled Figure 1. Debug output showing ChunkOverlapTransformer carrying complete trailing sentences into the next chunk without breaking multi-byte characters.


Metadata enrichment for filtering and RBAC

After chunking, attach business metadata to every Document. Copying doc.metadata into a new HashMap keeps the original page_number intact while adding fields you’ll filter on later with Filter.Expression in a pgvector store:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class SourceMetadataEnricher(
    private val department: String?,
    private val author: String?
) : DocumentTransformer {

    override fun apply(documents: List<Document>): List<Document> {
        val now = Instant.now().toString()
        val total = documents.size

        return documents.mapIndexed { index, doc ->
            val meta = HashMap(doc.metadata).apply {
                put("chunk_index", index)
                put("total_chunks", total)
                put("ingested_at", now)
                department?.let { put("department", it) }
                author?.let { put("author", it) }
            }
            Document(doc.id, doc.text, meta)
        }
    }
}

Verifying the ETL pipeline

Running unit and integration tests

The test suite generates an in-memory PDF via PDFBox and a sample Markdown file, then asserts chunk counts, sentence overlap flags, and preserved metadata keys:

1
./gradlew :rag-etl:test

Console output showing passing RAG ETL unit and integration tests Figure 2. Passing tests covering PDF parsing, TokenTextSplitter chunking, sentence overlap, and metadata preservation.

Calling the PDF chunking endpoint

Upload a real PDF with custom chunkSize, overlapTokens, department, and author query parameters:

1
2
curl -s -F "file=@handbook.pdf" \
  "http://localhost:8093/api/etl/chunks?chunkSize=300&overlapTokens=50&department=HR&author=NamjuKim" | jq .

JSON response showing 7 enriched chunks from handbook.pdf Figure 3. JSON output showing handbook.pdf split into 7 chunks with chunk_index, page_number, and department metadata populated.


Production caveats and checklist

Watch out for scanned PDFs and tables: PagePdfDocumentReader extracts embedded text streams via PDFBox. If someone uploads a scanned image-only PDF, it returns empty strings without throwing an error. Similarly, complex multi-column tables can scramble reading order. Always assert non-blank extracted text before writing to your vector store, and route scanned files through OCR or a multimodal extraction step first.

Before running this ingestion pipeline on production documents, double-check these items:

  • Empty-text guard: Reject or flag documents where PagePdfDocumentReader extracts zero characters (common with scanned PDFs).
  • Sentence-boundary overlap: Chain ChunkOverlapTransformer after TokenTextSplitter so boundary facts and multi-byte words stay intact.
  • Stable document IDs: If you re-ingest an updated handbook, generate deterministic IDs (or delete old chunks by file_name metadata first) so stale policy versions don’t linger in vector search.
  • RBAC metadata at ingest time: Populate department, tenant_id, or access_level during ETL—retrofitting access filters after embedding millions of rows is painful.
This post is licensed under CC BY 4.0 by the author.