Spring AI RAG: Build a Chat-with-PDF App Using Tika and Qdrant

  • Last Updated:
  • By: javahandson
  • Series
img

Spring AI RAG: Build a Chat-with-PDF App Using Tika and Qdrant

Spring AI RAG made simple. Build a Chat-with-PDF app using Apache Tika and Qdrant on Spring AI 2.0.1 — ingest a PDF, store vectors, and answer questions.

1. Introduction

Most Spring AI demos answer from what the model already knows. That feels great for a quick test. But real work needs answers from your own files, like a company policy PDF or a product manual. This is exactly where Spring AI RAG comes in, and in this guide we will build a simple Chat-with-PDF app step by step.

In the earlier articles, we looked at prompt stuffing and why it breaks down for large documents. Now we take the next step. We will read a PDF with Apache Tika, store it in Qdrant, and let the model answer questions from that PDF. So the app stops guessing and starts reading your document first.

By the end of this guide, you will know:

  • why prompt stuffing is not enough for real documents
  • how RAG works in three plain steps: retrieve, augment, generate
  • the way to set up Qdrant as a vector store in Spring AI 2.0.1
  • reading a PDF with Apache Tika and splitting it into chunks
  • two clean ways to answer questions, the manual approach and the advisor approach

Let us get started.

2. Why Do We Even Need RAG?

Let me start with a simple question. If we can paste text into the prompt, why do we need anything fancy?

The honest answer is that pasting works only for small text. The moment your documents grow, this trick falls apart. So teams move to RAG instead.

2.1 Prompt Stuffing in One Line

Prompt stuffing means you give the model an open book before it answers. You add the reference text along with the user question. Then the model reads that text and replies. People also call this in-context learning.

For a short HR note, this is perfectly fine. You paste the note, ask the question, and get a clean answer. No vector store, no extra setup.

2.2 Where Prompt Stuffing Breaks

Now imagine a 200-page policy document instead of a short note. Suddenly, two problems show up:

  • The prompt becomes huge, so you burn a lot of tokens and money on every call.
  • Only a tiny part of that text actually answers the question. The rest is noise.

Large context also hurts quality. Models tend to miss facts buried in the middle of a long prompt. People often call this the “lost in the middle” problem. As a result, a bigger prompt can give you a worse answer, not a better one.

2.3 The RAG Idea

Spring AI RAG fixes this in a neat way. Instead of sending the whole document, it breaks the document into small chunks. For each question, it fetches only the few chunks that match. Then it adds just those chunks to the prompt.

So the prompt stays small and focused. You save tokens, and the model sees only the text it needs. In short, RAG keeps the good part of prompt stuffing and drops the waste.

💡 Interview Insight
A common opening question is: “When would you choose prompt stuffing over RAG?” The honest answer earns points. Say prompt stuffing is fine for a small, fixed set of text that fits in the context window. Then say you move to RAG once documents grow large, change often, or when token cost and the lost-in-the-middle problem start to hurt.

3. What Is RAG, Step by Step?

RAG stands for Retrieval Augmented Generation. The name sounds heavy, but the idea is light. It is just three steps working together.

3.1 The Three Steps

Here is the whole flow in plain words:

  • Retrieval: search your documents and pull out the most relevant chunks.
  • Augmentation: add those chunks to the user prompt as context.
  • Generation: let the model write an answer using that context.

So the model is no longer answering from memory alone. Instead, it answers from your document plus its own language skills. That mix is what makes the answer accurate and grounded.

3.2 A Quick Analogy

Think of a student in an open-book exam. Without the book, the student guesses from memory. With the book, the student first finds the right page, reads it, and then writes the answer.

RAG does the same thing for the model. The vector store is the book. Retrieval is finding the right page. Generation is writing the final answer.

Spring AI RAG Chat-with-PDF flow diagram showing ingestion (PDF, Tika reader, text splitter, embedding model, Qdrant) and query (user, retriever, augment, LLM, answer)

3.3 The Two Phases You Must Remember

People often mix up when each step runs. So keep these two phases clear in your head:

  • Ingestion phase: this runs once, usually at startup. You read the PDF, split it, turn chunks into vectors, and store them in Qdrant.
  • Query phase: this runs on every question. You search Qdrant, grab the top chunks, and send them to the model.

The diagram above shows both phases together. Ingestion fills the store one time. After that, each question only searches and answers. This split is the heart of every RAG app.

4. Vector Store and Qdrant Basics

Before the code, let us understand the storage part. RAG needs a special kind of database called a vector store. Qdrant is one popular choice, and Spring AI supports it out of the box.

4.1 What Is a Vector Store?

A vector store keeps data as vectors. A vector is just a long list of numbers. These numbers capture the meaning of a piece of text, not its exact words.

Because of this, a vector store can search by meaning. A plain database searches by exact keywords. So if you ask “how to fix a laptop screen”, a vector store can still find text about “repairing a broken display”. The words differ, but the meaning matches.

4.2 Vector Store vs Traditional Database

The difference becomes clear with a small comparison:

  • A traditional database stores rows and columns. It searches with keywords or SQL. It is great for orders, users, and reports.
  • A vector store stores text as vectors. It searches by semantic meaning using similarity. It is built for AI search and RAG.

So you do not replace your main database. Instead, you add a vector store next to it, just for the AI search part.

4.3 Why Qdrant?

Qdrant is fast, open source, and easy to run with Docker. Spring AI also ships a ready starter for it. So you get auto-configuration and a clean VectorStore bean without much wiring.

One small but important detail. Spring AI talks to Qdrant over gRPC, on port 6334. The port 6333 is the REST API, which is handy for the Qdrant dashboard. Beginners often point Spring AI at 6333 by mistake, and then nothing connects.

💡 Interview Insight
Interviewers like to ask how semantic search differs from keyword search. Keep it short. Keyword search matches exact words, so “laptop screen” misses “broken display”. Semantic search matches meaning through vectors, so both map to nearby points and the right chunk is still found.

5. Setting Up the Project

Now we move to the real work. This guide uses Spring AI 2.0.1, which is the current stable release. It runs on Spring Boot 4 and needs Java 21. We will use OpenAI for the model and embeddings, and Qdrant for storage.

5.1 Add the Dependencies

First, add the needed starters in your pom.xml. I am assuming the Spring AI BOM is already in place, as shown in the earlier articles.

<!-- OpenAI: chat + embedding model -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

<!-- Qdrant vector store starter -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-qdrant</artifactId>
</dependency>

<!-- Apache Tika: reads PDF, DOCX, HTML and more -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-tika-document-reader</artifactId>
</dependency>

<!-- Docker Compose support (optional, to run Qdrant) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-docker-compose</artifactId>
    <scope>runtime</scope>
</dependency>

A few quick notes on these starters:

  • The OpenAI starter gives you both a chat model and an embedding model. RAG needs both.
  • The Qdrant starter auto-creates a VectorStore bean for you.
  • The Tika reader handles many file types, not just PDF.

5.2 Run Qdrant with Docker

Next, we need a Qdrant instance. The easiest way is Docker Compose. Add a compose.yml file in your project root:

services:
  qdrant:
    image: 'qdrant/qdrant:latest'
    ports:
      - '6333:6333'   # REST API and dashboard
      - '6334:6334'   # gRPC, used by Spring AI

With the Docker Compose starter on the classpath, Spring Boot starts this container when the app boots. So you do not run any extra command by hand. The container comes up with your app and goes down with it.

5.3 Configure the Properties

Now add the settings in application.properties. These cover both OpenAI and Qdrant:

# OpenAI
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=gpt-4o-mini
spring.ai.openai.embedding.model=text-embedding-3-small

# Qdrant
spring.ai.vectorstore.qdrant.host=localhost
spring.ai.vectorstore.qdrant.port=6334
spring.ai.vectorstore.qdrant.collection-name=chat-with-pdf
spring.ai.vectorstore.qdrant.initialize-schema=true

Let me explain the Qdrant lines, since they trip up many beginners:

  • The port is 6334, the gRPC port. Do not use 6333 here.
  • The collection-name is like a table name inside Qdrant. Pick any clear name.
  • The initialize-schema flag tells Spring AI to create that collection on startup. Without it, your first write fails.

Also, keep the API key in an environment variable. Never commit it to Git. This is a basic habit, but it saves a lot of pain later.

6. Ingestion: Read the PDF and Store It

This is the first phase of RAG. Here we read the PDF, split it into chunks, and push those chunks into Qdrant. This runs only once, at startup.

6.1 Read the PDF with Tika

Apache Tika can read many formats, so we lean on it here. Spring AI wraps it in a class called TikaDocumentReader. You give it a file, and it hands back a list of Document objects.

Here is a loader that runs at startup and fills the vector store:

@Component
public class PdfDataLoader {

    private final VectorStore vectorStore;

    @Value("classpath:Eazybytes_HR_Policies.pdf")
    private Resource pdfFile;

    public PdfDataLoader(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    @PostConstruct
    public void loadPdf() {
        // 1. Read the PDF into documents
        TikaDocumentReader reader = new TikaDocumentReader(pdfFile);
        List<Document> docs = reader.get();

        // 2. Split long text into smaller chunks
        TokenTextSplitter splitter = TokenTextSplitter.builder()
                .withChunkSize(300)
                .build();
        List<Document> chunks = splitter.split(docs);

        // 3. Embed and store the chunks in Qdrant
        vectorStore.add(chunks);
    }
}

The flow reads top to bottom, and each step has one job:

  • TikaDocumentReader pulls the raw text out of the PDF.
  • TokenTextSplitter cuts that text into chunks of about 300 tokens.
  • vectorStore.add(…) turns each chunk into a vector and saves it in Qdrant.

Notice one thing about vectorStore.add(…). You never call the embedding model yourself. Spring AI does it for you behind the scenes, using the embedding model from your config. So the code stays short and clean.

6.1.1 A Note on Chunk Size

Chunk size matters more than it looks. Small chunks give precise matches but may lose context. Large chunks keep context but can pull in extra noise. A size around 300 to 500 tokens works well for most policy or manual PDFs. So start there, then tune it based on your results.

6.1.2 A Small Change in Spring AI 2.0.1

Spring AI 2.0.1 made TokenTextSplitter stricter. Earlier, a wrong builder value could fail silently and give you one giant chunk. Now the builder checks its arguments and fails fast with a clear error. So if you see a validation error here, read it carefully. It is Spring AI helping you, not fighting you.

💡 Interview Insight
A frequent question is why we split documents before storing them. Explain the two reasons. First, embedding models have an input limit, so very long text cannot be embedded in one shot. Second, smaller chunks give sharper similarity matches, so the model receives only the relevant lines instead of whole pages.

7. Query: Answer Questions the Manual Way

Now the store is full. So we move to the second phase, the query phase. First, we will do it the manual way. This shows every step clearly, which helps you understand what really happens.

7.1 The Manual Flow

The manual approach has four small steps for each question:

  • Run a similarity search in Qdrant with the user question.
  • Collect the top matching chunks.
  • Join those chunks into a single context string.
  • Send the context plus the question to the model.

Here is a controller that does all four steps:

@RestController
@RequestMapping("/api")
public class DocumentChatController {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    public DocumentChatController(ChatClient.Builder builder,
                                  VectorStore vectorStore) {
        this.chatClient = builder.build();
        this.vectorStore = vectorStore;
    }

    @GetMapping("/document/chat")
    public String documentChat(@RequestParam String message) {

        // 1. Similarity search for the top chunks
        SearchRequest searchRequest = SearchRequest.builder()
                .query(message)
                .topK(3)
                .similarityThreshold(0.5)
                .build();
        List<Document> similarDocs =
                vectorStore.similaritySearch(searchRequest);

        // 2. Join the chunks into one context string
        String context = similarDocs.stream()
                .map(Document::getText)
                .collect(Collectors.joining(System.lineSeparator()));

        // 3. Send context + question to the model
        return chatClient.prompt()
                .system("Answer using only the context below.\n" + context)
                .user(message)
                .call()
                .content();
    }
}

Let me unpack the search settings, because they control answer quality:

  • topK(3) means fetch the three closest chunks. More chunks give more context but cost more tokens.
  • similarityThreshold(0.5) drops weak matches. A chunk must be at least 50 percent similar to count.

So these two knobs decide how much context reaches the model. Start small, then raise topK only if answers feel thin.

7.2 Test It

Run the app and try a question that your PDF can answer:

curl "http://localhost:8080/api/document/chat?message=How+many+paid+leaves+do+employees+get"

If the answer matches your PDF, your RAG pipeline works end to end. The model read your document, not the open internet. That is the whole point.

💡 Interview Insight
Interviewers often ask what topK and the similarity threshold do. Keep the answer concrete. topK caps how many chunks you retrieve, which controls context size and token cost. The threshold filters out weak matches, so irrelevant chunks never reach the prompt. Tune both to balance accuracy against cost.

8. Query: The Cleaner Way with Advisors

The manual approach is great for learning. But it has repeated plumbing in every endpoint. So Spring AI gives us advisors to hide that plumbing. Let us see two of them.

8.1 QuestionAnswerAdvisor

The QuestionAnswerAdvisor does the search and the context building for you. You just attach it to the ChatClient. Then you call the model as usual.

@GetMapping("/qa/chat")
public String qaChat(@RequestParam String message) {

    var qaAdvisor = QuestionAnswerAdvisor.builder(vectorStore)
            .searchRequest(SearchRequest.builder()
                    .topK(3)
                    .similarityThreshold(0.5)
                    .build())
            .build();

    return chatClient.prompt()
            .advisors(qaAdvisor)
            .user(message)
            .call()
            .content();
}

See how short this is. The advisor runs the similarity search, adds the chunks to the prompt, and calls the model. So all that manual code from section 7 is gone. Note that this advisor lives in the spring-ai-vector-store-advisor module.

8.1.1 A Dependency Rename to Know

Here is a point that confuses many developers after an upgrade. In the Spring AI 1.x era, this advisor sat in a module called spring-ai-advisors-vector-store. From 2.0 onward, that module was renamed to spring-ai-vector-store-advisor. So if an old tutorial fails to compile, check the artifact name first.

8.2 RetrievalAugmentationAdvisor

Spring AI also offers a more powerful advisor for RAG. It is the RetrievalAugmentationAdvisor, and it lives in the spring-ai-rag module. This one is built on a modular RAG design, so you can plug in extra steps later.

First, define the advisor as a bean:

@Bean
RetrievalAugmentationAdvisor ragAdvisor(VectorStore vectorStore) {
    return RetrievalAugmentationAdvisor.builder()
            .documentRetriever(
                    VectorStoreDocumentRetriever.builder()
                            .vectorStore(vectorStore)
                            .topK(3)
                            .similarityThreshold(0.5)
                            .build())
            .build();
}

Then use it in your controller like any other advisor:

@GetMapping("/rag/chat")
public String ragChat(@RequestParam String message) {
    return chatClient.prompt()
            .advisors(ragAdvisor)
            .user(message)
            .call()
            .content();
}

The VectorStoreDocumentRetriever handles the search. The advisor then adds the results to the prompt and calls the model. So your controller stays tiny, even as the pipeline grows.

8.2.1 Is It Still Experimental?

Many older blogs call this advisor “experimental”. That label came from the Spring AI 1.0 days. In the current 2.0.1 docs, it is described as an out-of-the-box advisor for common RAG flows, based on a modular architecture. So it is safe to use. Still, as with any feature, test it well before you ship.

💡 Interview Insight
A sharp interview question is the difference between QuestionAnswerAdvisor and RetrievalAugmentationAdvisor. Say both do RAG. QuestionAnswerAdvisor is the simpler one from the vector-store-advisor module. RetrievalAugmentationAdvisor sits in the spring-ai-rag module and follows a modular design, so you can add pre-retrieval and post-retrieval steps like query rewriting or reranking later.

9. Naive RAG vs Advanced RAG

What we built so far is called Naive RAG. It works well and is a solid start. But production apps often need more. That is where Advanced RAG helps.

9.1 What Naive RAG Does

Naive RAG is the simple path. You take the user question, search the store, and pass the top chunks straight to the model. There is no cleanup before or after the search.

For many apps, this is enough. So do not add complexity until you actually need it. Ship the simple version first, then measure.

9.2 What Advanced RAG Adds

Advanced RAG adds extra steps around the search. These steps fall into two groups:

  • Pre-retrieval: improve the question before the search. For example, rewrite a messy query or expand it into several clearer queries.
  • Post-retrieval: clean the results after the search. For example, rerank chunks by relevance, drop duplicates, or compress long text.

Post-retrieval also tackles the lost-in-the-middle problem. By reranking and trimming, you put the best chunks where the model notices them. So the final answer improves without a bigger prompt.

9.3 When to Go Advanced

My simple rule is this. Start with Naive RAG and watch the answers. If answers miss the point, look at pre-retrieval first. If the right chunks are found but the answer is still weak, look at post-retrieval. So you add only the step that fixes your real problem, not every step at once.

10. Best Practices and Common Mistakes

Let me share a few lessons that will save you debugging time. These come from building RAG apps the hard way.

10.1 Best Practices

  • Keep the ingestion code in one place, so you always know where documents get loaded.
  • Tune chunk size, topK, and the similarity threshold together, since they affect each other.
  • Log which chunks were retrieved for a question. This helps a lot when an answer looks wrong.
  • Tell the model to answer only from the given context. This reduces made-up answers.
  • Reload the store when the source PDF changes, or your answers will go stale.

10.2 Common Mistakes

  • Pointing Spring AI at Qdrant port 6333 instead of 6334. Nothing connects, and the error is confusing.
  • Forgetting initialize-schema=true, so the first write fails because the collection does not exist.
  • Setting the similarity threshold too high, so no chunks match and the model answers from memory.
  • Using a tiny chunk size, so each chunk loses the context around it.
  • Copying old 1.x code with the module name spring-ai-advisors-vector-store, which no longer exists.
💡 Interview Insight
A good closing question is how you would debug a RAG app that gives wrong answers. Walk through the pipeline. First, check that ingestion actually stored chunks. Next, log the retrieved chunks for the failing question. If the right chunks are missing, fix chunking or the threshold. If the chunks are correct but the answer is wrong, fix the prompt or try a stronger model.

11. FAQ’s on spring ai rag

Q: What is Spring AI RAG?

A: Spring AI RAG is Retrieval Augmented Generation built with the Spring AI framework. It reads your documents, stores them as vectors in a vector store like Qdrant, and fetches the most relevant chunks for each question. Those chunks are added to the prompt, so the model answers from your data instead of guessing from memory.

Q: What is the difference between prompt stuffing and RAG in Spring AI?

A: Prompt stuffing pastes the whole reference text into the prompt. It works for small, fixed text. RAG splits documents into chunks and fetches only the matching chunks per question. So RAG keeps the prompt small, saves tokens, and avoids the lost-in-the-middle problem that hurts large prompts.

Q: Which Qdrant port does Spring AI use?

A: Spring AI talks to Qdrant over gRPC on port 6334. Port 6333 is the REST API and dashboard. Set spring.ai.vectorstore.qdrant.port=6334 in your properties, and also set initialize-schema=true so the collection is created on startup.

Q: Which dependency do I need for RetrievalAugmentationAdvisor?

A: You need the spring-ai-rag module for RetrievalAugmentationAdvisor and VectorStoreDocumentRetriever. The simpler QuestionAnswerAdvisor lives in spring-ai-vector-store-advisor. Note that this advisor module was called spring-ai-advisors-vector-store in Spring AI 1.x, so old code may not compile until you fix the name.

Q: Is RetrievalAugmentationAdvisor still experimental in Spring AI 2.0.1?

A: No. The experimental label came from the Spring AI 1.0 days. The current 2.0.1 reference describes it as an out-of-the-box advisor for common RAG flows, based on a modular architecture. It is safe to use, though you should still test it before shipping.

Q: How do I read a PDF in Spring AI for RAG?

A: Use TikaDocumentReader from the spring-ai-tika-document-reader module. Point it at the PDF, call get() to read the text, split the text with TokenTextSplitter, then call vectorStore.add() to embed and store the chunks. Tika also reads DOCX, HTML, and many other formats, not just PDF.

12. Conclusion

Building a Chat-with-PDF app with Spring AI RAG is easier than it first looks. You read a PDF, store it as vectors, and let the model answer from those vectors. So the model stops guessing and starts reading your document. That shift is the real power of Spring AI RAG.

Here is a quick recap of the steps:

  • Add the OpenAI, Qdrant, and Tika starters.
  • Run Qdrant with Docker and point Spring AI at port 6334.
  • Read the PDF with Tika, split it, and store the chunks in Qdrant.
  • Answer questions with the manual flow, or lean on an advisor.
  • Move to Advanced RAG only when Naive RAG stops being enough.

Start small with one PDF and the manual flow. Then switch to the advisor approach to keep your code clean. After that, add advanced steps as your needs grow. This way, you get a working RAG app without making the code hard to follow.

13. Further Reading

Leave a Comment