Spring AI Vector Store: Setting Up Qdrant with Docker Compose

  • Last Updated:
  • By: javahandson
  • Series
img

Spring AI Vector Store: Setting Up Qdrant with Docker Compose

Set up a Spring AI vector store with Qdrant and Docker Compose. Learn the Spring AI 2.0 dependencies, properties, data loading, and similarity search.

1. Introduction

Most Spring AI demos keep everything in memory. That is fine when you are just testing a prompt. However, real apps need to search through documents, remember long chats, and find answers by meaning. For that, you need a Spring AI vector store. In this guide, we will set up Qdrant as our vector store and run it with Docker Compose.

In the earlier articles, we looked at chat models, chat memory, and embeddings. Now we join these ideas together. We will store embeddings in Qdrant. Then we will search them by meaning and feed the results to the LLM.

By the end of this guide, you will know:

  • what a vector store is, and why RAG needs one
  • why many teams pick Qdrant for this job
  • how to run Qdrant locally with Spring Boot Docker Compose
  • the exact Spring AI 2.0 dependencies and properties to use
  • how to load documents and run a similarity search
  • a few traps that catch beginners, and how to avoid them

Let us get started.

2. What Is a Vector Store?

Let me start with the basic idea. A vector store is a database built to store and search vectors. A vector is just a long list of numbers. These numbers capture the meaning of some text, image, or audio.

An AI model called an embedding model creates these numbers. Text that means similar things gets similar vectors. So the words “car” and “automobile” land close together, even though the letters differ.

2.1 Why Not a Normal Database?

A normal database is great at exact matches. You ask for user id 42, and you get that exact row. But meaning does not work like that. A user may ask “how do I fix a cracked screen?” while your document says “repairing a broken display.”

A keyword search misses this. The words do not match, so the search returns nothing useful. A vector store, on the other hand, compares meaning. As a result, it finds the right document even when the words are different.

Here is the difference at a glance:

  • A normal database matches exact text or runs SQL queries.
  • Vector stores match meaning using vector distance, such as cosine similarity.
  • Normal databases suit CRUD operations and reports.
  • Meanwhile, a vector store suits search, recommendations, and RAG.

2.2 Where the Spring AI Vector Store Fits

Spring AI gives you one common interface called VectorStore. Behind it, you can plug in many databases. For example, you can use Qdrant, Redis, PostgreSQL with pgvector, or others. Your code stays the same. Only the configuration changes.

This is the usual Spring style. You write against an abstraction. Then you swap the implementation without touching your business logic. So moving from one vector store to another is mostly a dependency and property change.

2.3 How the Vector Store Powers RAG

A vector store is the engine behind RAG, which stands for Retrieval Augmented Generation. The idea is simple. You give the LLM extra context from your own data before it answers. That way, the model does not have to guess.

The flow has three clear steps. First, you convert your documents into vectors and store them. Second, when a user asks a question, you turn the question into a vector too. Third, you search the store for the closest document vectors. Then you pass those documents to the LLM as context.

Without a vector store, you would stuff every document into the prompt. That wastes tokens and often confuses the model. With a vector store, you fetch only the few chunks that matter. So the prompt stays small, focused, and cheap.

💡 Interview Insight
Interviewers often ask what a vector store adds over a normal database. Keep the answer short. A normal database matches exact keys, while a vector store matches meaning through vector similarity. That single difference is what makes semantic search and RAG possible.
Spring AI vector store flow: documents go through an embedding model into a Qdrant collection, then a user query runs a similarity search to retrieve context for the LLM

3. Why Qdrant?

Spring AI supports many vector stores. So why do we pick Qdrant here? There are a few simple reasons.

First, Qdrant is open source and free to run locally. You do not need a cloud account or a credit card to start. Second, it is fast. Qdrant is written in Rust, and it talks over gRPC for low latency. Third, it runs as a small Docker container. Therefore, it fits perfectly with Spring Boot Docker Compose support.

A few more points make Qdrant friendly for learning:

  • It ships with a web dashboard, so you can see your data in the browser.
  • It stores vectors inside named collections, which is easy to reason about.
  • Spring AI has a ready starter for it, so auto-configuration does the heavy lifting.

To be fair, Qdrant is not the only good choice. If you already run PostgreSQL, pgvector may save you a database. If you already run Redis, that works too. Still, for a fresh project and a clean demo, Qdrant is hard to beat.

3.1 A Quick Comparison

Here is how Qdrant stacks up against two other popular options. Treat this as a rough guide, not a hard rule:

  • Qdrant is a dedicated vector database, so semantic search is its core job.
  • pgvector adds vectors to PostgreSQL, which is handy if you already use Postgres.
  • Redis is fast and flexible, but you often run it for cache and queues too.

Notice that each option shares the same Spring AI VectorStore interface. Therefore, your Java code barely changes between them. You mostly swap the starter dependency and a few properties. That portability is one of the best parts of Spring AI.

4. Qdrant Ports and Collections

Before we write code, let us understand two small things about Qdrant. Both come up again later, so they are worth a minute now.

4.1 Two Ports: 6333 and 6334

Qdrant exposes two ports, and they are not the same:

  • Port 6333 is the REST API. You use it for the web dashboard and for manual checks in the browser.
  • Port 6334 is the gRPC API. Spring AI talks to Qdrant over this port for speed.

This trips up many beginners. They point Spring AI at 6333 and then wonder why nothing connects. So remember the rule. Spring AI uses 6334, while you use 6333 in the browser.

4.2 Collections Hold Your Vectors

Qdrant groups vectors into collections. A collection is a bit like a table in a normal database. Each collection has a fixed vector size and a distance metric, such as cosine similarity.

In Spring AI, you give the collection a name through a property. If the collection does not exist yet, Spring AI can create it for you. However, you must opt in to that behavior, as we will see soon.

5. Setting Up Qdrant with Docker Compose

Now comes the fun part. We will run Qdrant with Docker Compose and let Spring Boot manage the container. This guide uses Spring AI 2.0, the current release line. Make sure Docker is installed and running first.

5.1 Define the Qdrant Service

Create a file named compose.yaml in your project root. Then add the Qdrant service like this:

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

A few notes on this file:

  • Spring Boot reads this compose file at startup and starts the container for you.
  • Both ports are mapped, so you get the dashboard and the gRPC endpoint.
  • When the app stops, Spring Boot can stop the container too, which keeps things tidy.

5.2 Add the Dependencies

Next, add the required dependencies to your pom.xml. I am assuming the Spring AI BOM is already in place from the earlier articles. Here are the four pieces you need:

<!-- Lets Spring Boot start and stop the Qdrant container -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-docker-compose</artifactId>
    <scope>runtime</scope>
</dependency>
 
<!-- Qdrant vector store starter (Spring Boot auto-configuration) -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-qdrant</artifactId>
</dependency>
 
<!-- Core RAG module: RetrievalAugmentationAdvisor lives here -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-rag</artifactId>
</dependency>
 
<!-- QuestionAnswerAdvisor and VectorStoreChatMemoryAdvisor live here -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-vector-store-advisor</artifactId>
</dependency>

The starter is the important one. With spring-ai-starter-vector-store-qdrant on the classpath, Spring Boot creates a VectorStore bean backed by Qdrant. You then inject that bean and use it.

One naming change deserves a flag here. In Spring AI 2.0, the advisor module was renamed. The old name was spring-ai-advisors-vector-store. The new name is spring-ai-vector-store-advisor. So if you copy an older tutorial, update this artifact id, or your build will fail.

💡 Interview Insight
A common interview question asks which module holds which advisor. Keep it clear. The RetrievalAugmentationAdvisor sits in spring-ai-rag. The QuestionAnswerAdvisor and VectorStoreChatMemoryAdvisor sit in spring-ai-vector-store-advisor. Mixing these up is a frequent build error in real projects.

5.3 Configure the Properties

Now tell Spring AI how to reach Qdrant. Add these lines to application.properties:

# Stop the Qdrant container when the app stops
spring.docker.compose.stop.command=down
 
# Qdrant connection settings
spring.ai.vectorstore.qdrant.host=localhost
spring.ai.vectorstore.qdrant.port=6334
spring.ai.vectorstore.qdrant.collection-name=javahandson
 
# Let Spring AI create the collection if it is missing
spring.ai.vectorstore.qdrant.initialize-schema=true

Let me explain the key properties:

  • The host is localhost, since Qdrant runs in a local container.
  • The port is 6334, which is the gRPC port. Do not use 6333 here.
  • The collection name is yours to choose. We use javahandson for this demo.
  • The initialize-schema flag asks Spring AI to create the collection if it does not exist.

5.4 The initialize-schema Gotcha in Spring AI 2.0

This one is important, so I will slow down. In Spring AI 2.0, the property spring.ai.vectorstore.qdrant.initialize-schema defaults to false. That is a breaking change. In older versions, schema creation happened by default.

What does this mean for you? If you forget this property, Spring AI will not create the collection. Then your first add or search fails, because the collection is missing. So set initialize-schema to true for a fresh demo. For production, many teams create the collection in advance with the exact vector size they want.

5.5 Check the Qdrant Dashboard

After you start the app, you can confirm that Qdrant is running. Open your browser and go to the REST port:

http://localhost:6333/dashboard

The dashboard shows your collections and the points inside them. So once you load some data, refresh this page. You should see your collection with a growing point count. This is a quick way to check that storage really worked.

6. Loading Data into the Vector Store

We have Qdrant running. Now let us put some data into it. In Spring AI, you add data as Document objects. The VectorStore then embeds each one and stores the vector.

6.1 A Simple Data Loader

Here is a small loader that pushes a few sentences into Qdrant at startup:

@Component
public class DataLoader {
 
    private final VectorStore vectorStore;
 
    public DataLoader(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }
 
    @PostConstruct
    public void loadData() {
        List<String> sentences = List.of(
            "Java is used for building scalable enterprise applications.",
            "Docker packages applications into lightweight containers.",
            "Spring AI connects Spring Boot apps to AI models.",
            "Qdrant is a fast vector database written in Rust."
        );
 
        List<Document> documents = sentences.stream()
                .map(Document::new)
                .toList();
 
        vectorStore.add(documents);
    }
}

Notice how little code this takes. You wrap each sentence in a Document. Then you call vectorStore.add(). Spring AI does the rest for you.

Behind the scenes, two things happen on that one add() call:

  • Spring AI calls the embedding model to turn each sentence into a vector.
  • It then stores the vector, the text, and any metadata as a point inside the Qdrant collection.

6.2 Loading from a PDF or Document

Hard-coded sentences are fine for a demo. Real apps load data from files. For that, Spring AI offers document readers. One handy reader uses Apache Tika, which handles PDFs, Word files, and more.

Add the Tika reader dependency first:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-tika-document-reader</artifactId>
</dependency>

Then read the file, split it into chunks, and store the chunks:

@Component
public class PolicyLoader {
 
    @Value("classpath:company-policy.pdf")
    private Resource policyFile;
 
    private final VectorStore vectorStore;
 
    public PolicyLoader(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }
 
    @PostConstruct
    public void loadPdf() {
        TikaDocumentReader reader = new TikaDocumentReader(policyFile);
        List<Document> docs = reader.get();
 
        TextSplitter splitter = TokenTextSplitter.builder()
                .withChunkSize(100)
                .withMaxNumChunks(400)
                .build();
 
        vectorStore.add(splitter.split(docs));
    }
}

Why split the document into chunks? Because a whole PDF is too big to search well. Small chunks give sharper matches. Also, small chunks keep your prompts short, which saves tokens later.

7. Searching the Vector Store

Storing data is only half the story. The real power is search. Let us run a similarity search against Qdrant and see what comes back.

To search, you build a SearchRequest and call similaritySearch(). Here is the simplest form:

List<Document> results = vectorStore.similaritySearch(
        SearchRequest.builder()
            .query("Tell me about containers")
            .topK(3)
            .build());

This asks Qdrant for the three closest documents to the query. Even though the query says “containers,” the Docker sentence should rank high. That is semantic search in action.

7.2 Add a Similarity Threshold

Sometimes you want only strong matches. A similarity threshold helps here. It drops results that are too weak:

SearchRequest searchRequest = SearchRequest.builder()
        .query(message)
        .topK(3)
        .similarityThreshold(0.5)
        .build();
 
List<Document> similarDocs = vectorStore.similaritySearch(searchRequest);

The threshold runs from 0 to 1. A higher value means stricter matching. So 0.5 is a balanced start. Later, you can tune it based on your own data and results.

7.3 Use the Results in a Chat

Now we close the loop. We take the search results, add them to the prompt, and ask the LLM. This is the heart of RAG. First, turn the documents into plain text:

String context = similarDocs.stream()
        .map(Document::getText)
        .collect(Collectors.joining(System.lineSeparator()));

Then feed that context to the ChatClient along with the user question:

String answer = chatClient.prompt()
        .system(spec -> spec.text(promptTemplate)
                .param("documents", context))
        .user(message)
        .call()
        .content();

The model now answers using your documents, not just its training data. As a result, the reply is grounded in your own content. That is exactly what we wanted.

💡 Interview Insight
An interviewer may ask how topK and the similarity threshold differ. Explain it simply. The topK value sets how many results you want back. The similarity threshold sets how close those results must be. You often use both together to keep the context small and relevant.

8. Letting Spring AI Do the RAG Work

The manual approach above is good for learning. You can see every step. However, it has repeated code. Spring AI offers a cleaner way with a built-in advisor.

8.1 The RetrievalAugmentationAdvisor

This advisor handles retrieval for you. It searches the vector store, builds the context, and adds it to the prompt. You just wire it once. Define the advisor bean like this:

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

Remember, this advisor lives in the spring-ai-rag module. So keep that dependency in your pom.xml.

8.2 Register the Advisor

Next, add the advisor to your ChatClient. Then the retrieval happens on every call, with no manual search:

@Bean
public ChatClient chatClient(ChatClient.Builder builder,
        RetrievalAugmentationAdvisor advisor) {
 
    return builder
            .defaultAdvisors(advisor)
            .build();
}

Now your controller is clean. You send the user message, and the advisor fetches the right context behind the scenes:

@GetMapping("/document/chat")
public String documentChat(@RequestParam String message) {
    return chatClient.prompt()
            .user(message)
            .call()
            .content();
}

See the difference? No SearchRequest. No manual joining of text. The advisor did all of that for us. For most apps, this is the way to go.

9. Best Practices and Common Mistakes

Let me share a few lessons that will save you debugging time. I have hit most of these myself.

9.1 Best Practices

  • Always set initialize-schema to true for demos, or create the collection in advance for production.
  • Keep the gRPC port 6334 for Spring AI, and use 6333 only in the browser.
  • Split large documents into small chunks before you store them.
  • Start with a similarity threshold near 0.5, then tune it with real queries.
  • Use the same embedding model for loading and for searching, so the vectors match.

9.2 Common Mistakes

  • Pointing Spring AI at port 6333 instead of 6334. The connection then fails.
  • Forgetting initialize-schema, which leaves the collection missing in Spring AI 2.0.
  • Using the old module name spring-ai-advisors-vector-store instead of spring-ai-vector-store-advisor.
  • Storing a whole PDF as one document, which gives weak, noisy search results.
  • Setting the threshold too high, so even good matches get dropped.
💡 Interview Insight
A frequent interview follow-up is why a Spring AI 2.0 app connects to Qdrant but finds no data. The usual cause is a missing collection. Since initialize-schema now defaults to false, the schema is never created unless you opt in. Mention this gotcha, and you show real hands-on experience.

10. FAQ’s on spring ai vector store

Q: What is a vector store in Spring AI?

A: A vector store is a database that stores text as vectors and searches it by meaning. Spring AI exposes one common VectorStore interface, so you can plug in Qdrant, pgvector, Redis, and others without changing your Java code.

Q: Which port does Spring AI use to connect to Qdrant?

A: Spring AI connects over the gRPC port 6334. Port 6333 is the REST API and web dashboard, which you open in the browser. Pointing Spring AI at 6333 is a common reason the connection fails.

Q: Why is my Qdrant collection missing in Spring AI 2.0?

A: In Spring AI 2.0, spring.ai.vectorstore.qdrant.initialize-schema defaults to false. This is a breaking change from older versions. Set it to true so Spring AI creates the collection, or create the collection in advance for production.

Q: What is the Qdrant starter dependency for Spring AI 2.0?

A: Use org.springframework.ai:spring-ai-starter-vector-store-qdrant. The older name spring-ai-qdrant-store-spring-boot-starter belongs to Spring AI 1.x, so update it if you copy an older tutorial.

Q: How do I load documents into a Spring AI vector store?

A: Wrap your text in Document objects and call vectorStore.add(documents). Spring AI embeds each document and stores it in the Qdrant collection. For PDFs, use TikaDocumentReader and split the text into small chunks first.

Q: What is the difference between topK and similarity threshold?

A: The topK value sets how many results you get back. The similarity threshold sets how close those results must be, on a scale of 0 to 1. You often use both together to keep the retrieved context small and relevant.

11. Conclusion

Setting up a Spring AI vector store with Qdrant is simpler than it first looks. Docker Compose runs the database for you. The starter wires everything up. Then a few properties connect the two.

Here is a quick recap of the steps:

  • Define the Qdrant service in compose.yaml with both ports.
  • Add the Docker Compose, Qdrant starter, and RAG dependencies.
  • Set the host, gRPC port, collection name, and initialize-schema.
  • Load documents with vectorStore.add().
  • Search with similaritySearch(), or let the RetrievalAugmentationAdvisor do it.

Start small with a handful of sentences and one search. Once that works, load a real PDF and switch to the advisor. This way, you build a solid RAG foundation without getting lost in the details.

12. Further Reading

Leave a Comment