Spring AI RAG: Build a Chat-with-PDF App Using Tika and Qdrant
-
Last Updated:
-
By: javahandson
-
Series

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.
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:
Let us get started.
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.
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.
Now imagine a 200-page policy document instead of a short note. Suddenly, two problems show up:
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.
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. |
RAG stands for Retrieval Augmented Generation. The name sounds heavy, but the idea is light. It is just three steps working together.
Here is the whole flow in plain words:
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.
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.

People often mix up when each step runs. So keep these two phases clear in your head:
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.
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.
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.
The difference becomes clear with a small comparison:
So you do not replace your main database. Instead, you add a vector store next to it, just for the AI search part.
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. |
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.
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:
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 AIWith 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.
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=trueLet me explain the Qdrant lines, since they trip up many beginners:
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.
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.
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:
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.
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.
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. |
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.
The manual approach has four small steps for each question:
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:
So these two knobs decide how much context reaches the model. Start small, then raise topK only if answers feel thin.
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. |
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.
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.
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.
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.
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. |
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.
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.
Advanced RAG adds extra steps around the search. These steps fall into two groups:
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.
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.
Let me share a few lessons that will save you debugging time. These come from building RAG apps the hard way.
| 💡 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. |
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.
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.
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.
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.
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.
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.
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:
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.