Spring › Spring-AI

Building RAG Q&A with PostgreSQL pgvector and Gemini embeddings

Connect PostgreSQL 17 pgvector and gemini-embedding-001 in Spring AI 2.0.1, work around HNSW dimension limits, and wire QuestionAnswerAdvisor.

Building RAG Q&A with PostgreSQL pgvector and Gemini embeddings

Introducing a standalone vector database like Pinecone, Milvus, or Qdrant adds another cluster to operate and forces you to keep embeddings in sync with relational tables. Adding the pgvector extension to PostgreSQL lets you run cosine similarity search alongside existing business data in one database. This post shows how to wire gemini-embedding-001, PostgreSQL 17 pgvector HNSW indexes, and Spring AI 2.0.1’s QuestionAnswerAdvisor into an end-to-end RAG endpoint.

Tested with Spring Boot 4.1.1, Spring AI 2.0.1, Kotlin 2.3.21, PostgreSQL 17 (pgvector/pgvector:pg17), and gemini-embedding-001. Full source is in spring-ai-examples (rag-pgvector).


How QuestionAnswerAdvisor orchestrates RAG

Instead of manually embedding every user question, querying VectorStore, and concatenating prompt strings inside your service layer, Spring AI’s QuestionAnswerAdvisor wraps the retrieval-and-augmentation step into a single ChatClient advisor.

flowchart TD
    Client["Client (POST /api/rag/ask)"] --> RagService["RagService + QuestionAnswerAdvisor"]
    RagService -->|"1. Embed question (768 dims)"| Embedding["Google GenAI (gemini-embedding-001)"]
    Embedding -->|"2. Cosine search (topK=3, filter)"| PgVector["PostgreSQL 17 (pgvector HNSW)"]
    PgVector -->|"3. Inject matching chunks + prompt"| Gemini["Google Gemini (gemini-3.5-flash-lite)"]
    Gemini -->|"4. Answer + qa_retrieved_documents"| Client

When chatClient.prompt().user(question).call() executes, the advisor intercepts the request, embeds the user text via the configured EmbeddingModel, runs a similarity search against VectorStore with your topK, similarityThreshold, and filterExpression, injects the returned chunks into {question_answer_context}, and stores the retrieved Document list in the response metadata under QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS.

PostgreSQL pgvector vs. dedicated vector databases

DimensionPostgreSQL pgvectorDedicated Vector DB (Qdrant / Milvus / Pinecone)
Operational footprintReuses existing PostgreSQL backup, monitoring, and HASeparate cluster, auth, and deployment pipeline
Transactional consistencyUpdate relational rows and vectors in one ACID transactionEventual consistency; requires outbox or CDC sync
Scale sweet spotThousands to ~tens of millions of vectorsHundreds of millions+ vectors with horizontal sharding
FilteringFull SQL + JSONB metadata filtersPurpose-built pre/post-filtering indexes

When not to use pgvector: If you need sub-20ms tail latency across hundreds of millions of embeddings or heavy concurrent write throughput that would starve your primary OLTP PostgreSQL instance, offload vector search to a dedicated engine (or at least isolate it onto a dedicated PostgreSQL instance).


Project setup and local container

Dependencies in build.gradle.kts

Include spring-ai-starter-vector-store-pgvector, the PostgreSQL JDBC driver, and Testcontainers for real-database integration tests (see my Testcontainers @ServiceConnection setup for container lifecycle details):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.boot:spring-boot-starter-jdbc")
    implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
    implementation("org.springframework.ai:spring-ai-starter-vector-store-pgvector")
    implementation("tools.jackson.module:jackson-module-kotlin")

    developmentOnly("org.springframework.boot:spring-boot-docker-compose")
    runtimeOnly("org.postgresql:postgresql")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.springframework.boot:spring-boot-testcontainers")
    testImplementation("org.testcontainers:postgresql")
}

Local pgvector 17 container (compose.yaml)

1
2
3
4
5
6
7
8
9
services:
  pgvector:
    image: pgvector/pgvector:pg17
    environment:
      POSTGRES_DB: rag
      POSTGRES_USER: rag
      POSTGRES_PASSWORD: rag
    ports:
      - "5432:5432"

Two Spring AI 2.0.1 + pgvector pitfalls to fix first

I hit two configuration traps immediately when wiring gemini-embedding-001 to pgvector in Spring AI 2.0.1. Both fail fast at startup if you miss them.

1. Separate embedding API key property

Watch out for split API key properties: The chat model reads spring.ai.google.genai.api-key, but the embedding auto-configuration reads spring.ai.google.genai.embedding.api-key separately. Setting only the top-level chat key causes embedding bean initialization to fail with a missing API key error. Set both properties explicitly.

2. Reducing gemini-embedding-001 from 3,072 to 768 dimensions

pgvector HNSW 2,000-dimension ceiling: gemini-embedding-001 outputs 3,072 dimensions by default, but pgvector’s HNSW index (vector type) caps at 2,000 dimensions. Letting Spring AI create a 3,072-dimension HNSW index fails with ERROR: column cannot be indexed with HNSW (maximum 2000 dimensions). Because Gemini embeddings use Matryoshka Representation Learning (MRL), truncating dimensions to 768 preserves retrieval quality while fitting cleanly under the HNSW limit and cutting storage by 4x.

Working application.yaml

Make sure dimensions: 768 matches in both the embedding block and the pgvector block:

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
server:
  port: 8094

spring:
  application:
    name: rag-pgvector
  datasource:
    url: jdbc:postgresql://localhost:5432/rag
    username: rag
    password: rag
  ai:
    google:
      genai:
        api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY}
        embedding:
          api-key: ${SPRING_AI_GOOGLE_GENAI_API_KEY} # Explicit key for embedding auto-config
          text:
            model: gemini-embedding-001
            dimensions: 768                           # Reduced from 3072 via MRL
    vectorstore:
      pgvector:
        initialize-schema: true                       # Auto-creates vector_store table
        index-type: hnsw
        distance-type: cosine-distance
        dimensions: 768                               # Must match embedding dimensions

PostgreSQL psql output showing vector(768) column and HNSW cosine index Figure 1. psql schema inspection confirming the vector(768) column and vector_cosine_ops HNSW index.


Implementing RagService with QuestionAnswerAdvisor

RagService builds a SearchRequest with an optional metadata filter (such as department == 'HR' populated during document ETL ingestion), binds QuestionAnswerAdvisor, and extracts the matched source documents from chatResponse.metadata so the caller can render citations:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
@Service
class RagService(
    private val vectorStore: VectorStore,
    private val chatClientBuilder: ChatClient.Builder
) {

    fun ask(question: String, filterExpression: String?): RagAnswerResponse {
        val searchRequestBuilder = SearchRequest.builder()
            .topK(3)
            .similarityThreshold(0.6)

        if (!filterExpression.isNullOrBlank()) {
            searchRequestBuilder.filterExpression(filterExpression)
        }

        val qaAdvisor = QuestionAnswerAdvisor.builder(vectorStore)
            .searchRequest(searchRequestBuilder.build())
            .userTextAdvise(
                """
                [Reference Documents]
                {question_answer_context}

                [Question]
                {user_text}

                Answer strictly based on the reference documents above.
                If the answer is not in the documents, state clearly that you do not know instead of guessing.
                """.trimIndent()
            )
            .build()

        val chatClient = chatClientBuilder.defaultAdvisors(qaAdvisor).build()
        val chatResponse = chatClient.prompt().user(question).call().chatResponse()

        val answer = chatResponse?.result?.output?.text ?: ""

        // Extract the source Documents injected into the prompt by the advisor
        @Suppress("UNCHECKED_CAST")
        val retrievedDocs = chatResponse?.metadata?.get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS)
            as? List<Document> ?: emptyList()

        val sources = retrievedDocs.map { doc ->
            SourceDocument(
                id = doc.id,
                score = doc.score,
                text = doc.text ?: "",
                metadata = doc.metadata
            )
        }

        return RagAnswerResponse(answer, sources)
    }
}

Verification

Unit and Testcontainers integration tests

Running the test suite boots a real pgvector/pgvector:pg17 container via Testcontainers, initializes the HNSW schema, verifies cosine search and metadata filtering, and exercises the end-to-end Gemini Q&A flow:

1
./gradlew :rag-pgvector:test

Console output showing passing PGvector RAG unit and integration tests Figure 2. Passing PgVectorStoreContainerTests and Gemini RAG integration tests.

Querying the RAG endpoint with a metadata filter

After ingesting the HR handbook chunks, send a question filtered to department == 'HR':

1
2
3
curl -s -X POST http://localhost:8094/api/rag/ask \
  -H "Content-Type: application/json" \
  -d '{"question": "Can unused annual leave roll over to next year?", "filterExpression": "department == '\''HR'\''"}' | jq .

Console output showing JSON response from QuestionAnswerAdvisor with citations Figure 3. Grounded answer generated from the retrieved HR handbook section along with source metadata.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "answer": "No. Under Article 14 of the employee handbook, unused annual leave expires after one year and does not roll over to the following year.",
  "sources": [
    {
      "id": "6f0c2a81-e2bc-4189-9132-7f289d0012ab",
      "score": 0.824,
      "text": "Article 14 (Expiration of Annual Leave): Unused paid annual leave expires one year from the grant date and does not carry over to the next year.",
      "metadata": {
        "author": "Namju Kim",
        "department": "HR",
        "file_name": "employee-handbook.pdf",
        "page_number": 3
      }
    }
  ]
}

Production caveats and checklist

Disable initialize-schema: true in production: Auto-creating tables on startup is convenient locally, but in production you should manage the vector_store table and its HNSW index through Flyway or Liquibase migrations. Also note that aggressive metadata filters combined with HNSW can return fewer than topK rows if PostgreSQL evaluates the filter after the HNSW scan—on pgvector 0.8+, enable iterative index scans (hnsw.iterative_scan = relaxed_order) when filtering selective metadata.

Before deploying a pgvector RAG service, check these four items:

  • Matching dimensions: embedding.text.dimensions and vectorstore.pgvector.dimensions both set to 768 (or another value <= 2,000 for vector HNSW).
  • Both API keys wired: spring.ai.google.genai.api-key and spring.ai.google.genai.embedding.api-key explicitly configured.
  • Threshold calibration: Tune similarityThreshold (start around 0.55–0.65 for cosine) against real queries so borderline matches aren’t silently dropped.
  • Schema managed by migrations: Turn off initialize-schema outside dev/test and track the HNSW index in your migration tool.
This post is licensed under CC BY 4.0 by the author.