RAG with Spring AI

Implementing RAG in Java with Spring AI 2.0: the ETL pipeline (DocumentReader, TokenTextSplitter, metadata enrichers, VectorStore), pgvector configuration, QuestionAnswerAdvisor, modular RetrievalAugmentationAdvisor with query rewriting, metadata and permission filters, and testing.

On this page

What we are building#

A Spring Boot service that ingests policy documents into PostgreSQL with pgvector, then answers questions with citations, filtered by the user’s department.

Spring AI RAG components
flowchart LR
    subgraph Ingest["Ingestion — ETL pipeline"]
        DR["DocumentReader<br/>PagePdfDocumentReader, TikaDocumentReader,<br/>MarkdownDocumentReader, JsonReader"] --> TS["DocumentTransformer<br/>TokenTextSplitter,<br/>KeywordMetadataEnricher,<br/>SummaryMetadataEnricher"]
        TS --> VW["DocumentWriter<br/>VectorStore.add()"]
    end
    VW --> PG[("PostgreSQL + pgvector<br/>vector_store table")]
    subgraph Query["Query"]
        CC["ChatClient"] --> RAA["RetrievalAugmentationAdvisor<br/>query transformers → retriever → augmenter"]
        RAA --> PG
        RAA --> LLM(("ChatModel"))
    end

Dependencies and configuration#

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-vector-store-advisor</artifactId>    <!-- QuestionAnswerAdvisor -->
</dependency>
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-rag</artifactId>                     <!-- RetrievalAugmentationAdvisor -->
</dependency>
<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-pdf-document-reader</artifactId>
</dependency>
<!-- plus a chat model starter and an embedding model starter, e.g. OpenAI or Bedrock -->
spring.datasource.url=jdbc:postgresql://localhost:5432/assistant
spring.ai.vectorstore.pgvector.initialize-schema=true
spring.ai.vectorstore.pgvector.index-type=HNSW
spring.ai.vectorstore.pgvector.distance-type=COSINE_DISTANCE
spring.ai.vectorstore.pgvector.dimensions=1536

The starter auto-configures a VectorStore bean using the EmbeddingModel bean from your embedding starter. In production, prefer creating the schema with your migration tool (Flyway/Liquibase) and set initialize-schema=false.

Ingestion: the ETL pipeline#

@Service
class PolicyIngestionService {

    private final VectorStore vectorStore;

    PolicyIngestionService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    void ingest(Resource pdf, String docId, String department, String version) {
        // 1. Extract: one Document per page, with page metadata
        List<Document> pages = new PagePdfDocumentReader(pdf).get();

        // 2. Transform: split into ~token-sized chunks
        List<Document> chunks = TokenTextSplitter.builder()
            .withChunkSize(500)
            .build()
            .apply(pages);

        // 3. Enrich: metadata used for filtering, citation and lifecycle
        chunks.forEach(chunk -> chunk.getMetadata().putAll(Map.of(
            "docId", docId,
            "department", department,
            "version", version,
            "source", pdf.getFilename())));

        // 4. Load: embed + store
        vectorStore.add(chunks);
    }

    void deleteDocument(String docId) {
        vectorStore.delete(new FilterExpressionBuilder().eq("docId", docId).build());
    }
}

Design notes:

  • Run ingestion asynchronously (a queue or batch job), not inside user requests.
  • Make it idempotent: delete the previous version’s chunks before adding the new version (or use deterministic chunk IDs).
  • Add the heading path / document title to chunk text for better retrieval (contextual headers).
  • Other transformers: KeywordMetadataEnricher and SummaryMetadataEnricher use an LLM to add keywords or summaries.

Simple RAG: QuestionAnswerAdvisor#

@Service
class PolicyAssistant {

    private final ChatClient chatClient;

    PolicyAssistant(ChatClient.Builder builder, VectorStore vectorStore) {
        this.chatClient = builder
            .defaultSystem("""
                Answer only from the provided context. Cite the 'source' metadata of each
                document you use. If the context does not contain the answer, say so.
                """)
            .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore)
                .searchRequest(SearchRequest.builder().topK(5).similarityThreshold(0.6).build())
                .build())
            .build();
    }

    String answer(String question, String department) {
        return chatClient.prompt()
            .user(question)
            .advisors(a -> a.param(QuestionAnswerAdvisor.FILTER_EXPRESSION,
                                   "department == '" + department + "'"))
            .call()
            .content();
    }
}

The advisor embeds the question, searches the vector store with the filter, and appends the documents to the prompt.

Modular RAG: RetrievalAugmentationAdvisor#

For advanced RAG, compose the pipeline from parts.

RetrievalAugmentationAdvisor pipeline
flowchart LR
    Q["Query"] --> QT["Query transformers<br/>RewriteQueryTransformer,<br/>CompressionQueryTransformer,<br/>TranslationQueryTransformer"]
    QT --> QE["Query expander<br/>MultiQueryExpander"]
    QE --> DR["Document retriever<br/>VectorStoreDocumentRetriever<br/>topK, threshold, filter"]
    DR --> JN["Document joiner<br/>merge + dedupe"]
    JN --> PP["Document post-processors<br/>rerank, compress"]
    PP --> QA["Query augmenter<br/>ContextualQueryAugmenter"]
    QA --> LLM(("ChatModel"))
@Bean
Advisor ragAdvisor(ChatClient.Builder builder, VectorStore vectorStore) {
    return RetrievalAugmentationAdvisor.builder()
        // Rewrite conversational / vague questions into good search queries
        .queryTransformers(RewriteQueryTransformer.builder()
            .chatClientBuilder(builder.build().mutate())
            .build())
        // Retrieve with a permission filter resolved per request from the security context
        .documentRetriever(VectorStoreDocumentRetriever.builder()
            .vectorStore(vectorStore)
            .topK(8)
            .similarityThreshold(0.5)
            .filterExpression(() -> new FilterExpressionBuilder()
                .in("department", currentUserDepartments().toArray())
                .build())
            .build())
        // Allow the model to say "I don't know" when nothing is retrieved
        .queryAugmenter(ContextualQueryAugmenter.builder()
            .allowEmptyContext(true)
            .build())
        .build();
}

Notes:

  • MultiQueryExpander generates paraphrases for better recall; TranslationQueryTransformer translates queries into the corpus language; CompressionQueryTransformer condenses chat history into a standalone query.
  • By default the advisor refuses to answer with empty context; allowEmptyContext(true) lets the model answer generally — choose deliberately.
  • Add a reranker as a document post-processor for production quality (call a rerank API or cross-encoder).
  • Hybrid search (BM25 + vectors) depends on the store: use a store with native hybrid support or combine a keyword retriever with the vector retriever and join results.

Returning sources#

To show citations, read retrieved documents from the response context:

ChatClientResponse response = chatClient.prompt()
    .user(question)
    .call()
    .chatClientResponse();

List<Document> docs = (List<Document>) response.context()
    .get(RetrievalAugmentationAdvisor.DOCUMENT_CONTEXT);
List<String> sources = docs.stream().map(d -> (String) d.getMetadata().get("source")).distinct().toList();

Testing the RAG service#

  • Integration tests with Testcontainers PostgreSQL + pgvector (spring-ai-spring-boot-testcontainers).
  • Evaluation tests with Spring AI’s RelevancyEvaluator and FactCheckingEvaluator on a golden dataset; see Spring AI in production.
  • Permission tests: a user from department A must never get chunks from department B.

Common mistakes#

Review questions#

How do you implement RAG with Spring AI? Ingest with the ETL pipeline: a DocumentReader (PDF, Tika, Markdown), TokenTextSplitter, metadata enrichment, then VectorStore.add() into pgvector or another store. At query time, add QuestionAnswerAdvisor for simple RAG or RetrievalAugmentationAdvisor for modular RAG with query transformers, a VectorStoreDocumentRetriever with filters, and a ContextualQueryAugmenter.

How do you enforce per-user access in Spring AI RAG? Store access metadata on each chunk and apply a filter expression on retrieval — built with FilterExpressionBuilder from the authenticated security context, via a Supplier so it is evaluated per request — never from user-supplied strings.

QuestionAnswerAdvisor vs RetrievalAugmentationAdvisor? QuestionAnswerAdvisor is a simple, ready-made RAG advisor: vector search plus prompt augmentation. RetrievalAugmentationAdvisor is modular: you plug in query transformers, expanders, retrievers, joiners, post-processors and augmenters for advanced RAG.

Summary#

  • Ingest with DocumentReader → TokenTextSplitter → metadata → VectorStore; run it async and idempotently.
  • pgvector via a starter and properties; manage schema with migrations in production.
  • QuestionAnswerAdvisor for simple RAG; RetrievalAugmentationAdvisor for modular, advanced RAG.
  • Filter by permissions using the type-safe builder and the security context; return sources for citations.

References#