Vector Databases with Spring AI – PGVector, Redis and MongoDB

In Spring AI, Vector Databases act as the persistent storage and retrieval layer for high-dimensional embeddings, enabling semantic similarity search and Retrieval-Augmented Generation (RAG). Through the unified VectorStore abstraction, Spring AI allows applications to swap or combine databases—such as PostgreSQL (pgvector), Redis, and MongoDB—without rewriting core ingestion or query logic.

1. Unified VectorStore Architecture

Across all supported vector databases, Spring AI standardizes storage and retrieval around three core mechanics:
  • Automatic Embedding Pipeline: Whenever documents are added (add) or queried via natural language (similaritySearch), the VectorStore automatically invokes the configured EmbeddingModel to compute vector arrays before executing database operations. (For pre-computed vectors, upsert is also supported.)

  • Token-Aware Batching (BatchingStrategy): Before sending large document sets to an embedding provider, Spring AI uses TokenCountBatchingStrategy to group chunks safely within the embedding model’s maximum token limit.

  • Portable Metadata Filtering: Spring AI defines a database-agnostic, SQL-like filter expression syntax (e.g., department == 'hr' && year >= 2025) that each store implementation translates into native database queries (SQL WHERE clauses, RediSearch tags/numerics, or MongoDB aggregation filters).

2. PostgreSQL with pgvector (PgVectorStore)

pgvector is an open-source extension that adds vector similarity search directly into standard PostgreSQL databases, making it ideal for teams that already run PostgreSQL and want transactional consistency alongside relational data.
  • Starter & Integration: Uses spring-ai-starter-vector-store-pgvector and reuses Spring Boot’s standard JdbcTemplate and PostgreSQL DataSource.

  • Storage Layout: Persists records inside a relational table (defaulting to public.vector_store) with columns for document UUIDs, text content, JSONB metadata, and the vector embedding column.

  • Indexing & Distance Metrics:

    • Index Types: Supports HNSW (Hierarchical Navigable Small World—default, fast queries, higher memory), IVFFlat (faster index build, lower memory), or NONE (exact nearest-neighbor scan).

    • Distance Functions: Supports Cosine Distance (default), Euclidean Distance (L2), and Negative Inner Product.

  • Operational Strengths: Inherits PostgreSQL backups, ACID transactions, role-based access control, and SQL joins without introducing a separate database server. Automatic table and extension initialization is opt-in via spring.ai.vectorstore.pgvector.initialize-schema=true.

3. Redis Vector Store (RedisVectorStore)

Redis (via Redis Stack or Redis 8+ with JSON and Query/Search modules) operates as an ultra-low-latency, in-memory vector database suited for real-time semantic search, session caching, and high-throughput retrieval.
  • Starter & Integration: Uses spring-ai-starter-vector-store-redis backed by Jedis and Spring Data Redis connection properties.

  • Storage Layout: Stores each Spring AI Document as a structured Redis JSON object (or Hash) prefixed under a configurable keyspace (e.g., embedding:), indexing both vector fields and metadata attributes inside a RediSearch index.

  • Indexing & Distance Metrics:

    • Index Algorithms: Supports HNSW for approximate nearest-neighbor speed and FLAT for exact brute-force precision on smaller datasets.

    • Distance Functions: Supports Cosine, L2 (Euclidean), and Inner Product (IP).

  • Metadata Schema Requirement: Unlike pgvector, Redis requires metadata fields used in filter expressions (TAG, NUMERIC, or TEXT fields) to be explicitly declared in configuration or bean setup so RediSearch indexes them for filtering.

  • Operational Strengths: Delivers sub-millisecond query performance and integrates cleanly when an application already uses Redis for caching or rate limiting.

4. MongoDB Vector Search (MongoDBAtlasVectorStore)

MongoDB provides native vector search capabilities through MongoDB Atlas or self-hosted MongoDB Community/Enterprise clusters equipped with Search (mongot), allowing operational JSON documents and vector embeddings to live in the same collection.
  • Starter & Integration: Uses spring-ai-starter-vector-store-mongodb-atlas built on top of MongoTemplate and Spring Data MongoDB.

  • Storage Layout: Stores each Spring AI Document as a native BSON document containing text content, nested metadata fields, and an array of floats representing the embedding vector.

  • Indexing & Search Mechanics:

    • Leverages MongoDB’s $vectorSearch aggregation pipeline stage powered by Apache Lucene HNSW indexes.

    • Supports pre-filtering metadata fields directly inside the $vectorSearch stage for high-efficiency scoped queries.

    • When spring.ai.vectorstore.mongodb.initialize-schema=true is enabled, Spring AI automatically creates the target collection and vector search index at startup.

  • Operational Strengths: Eliminates synchronization pipelines between an operational document database and an external vector store, supports storing multiple vector fields per document for multimodal search, and scales elastically on Atlas.

5. Comparison Matrix: PGVector vs. Redis vs. MongoDB

Dimension PostgreSQL (pgvector) Redis (RedisVectorStore) MongoDB (MongoDBAtlasVectorStore)
Database Paradigm Relational (SQL + vector extension) In-memory Key-Value / JSON store Distributed Document (BSON) store
Primary Storage Medium Disk-backed with shared memory buffers RAM-first (with AOF/RDB persistence) Disk-backed with WiredTiger cache
Vector Index Types HNSW, IVFFlat, Exact (NONE) HNSW, FLAT Lucene HNSW ($vectorSearch)
Metadata Filtering Dynamic on JSONB column; zero extra schema declaration needed Requires explicit declaration of filterable TAG / NUMERIC / TEXT fields Pre-filtered inside $vectorSearch using indexed BSON filter fields
Schema Initialization Opt-in (initialize-schema=true) creates extension, table, and index Opt-in (initialize-schema=true) creates RediSearch index Opt-in (initialize-schema=true) creates collection and Atlas Vector Search index
Best-Fit Scenario Apps already using Postgres needing ACID transactions, SQL joins, and zero new infra Ultra-low-latency search where working datasets fit comfortably in RAM Document-centric apps storing rich hierarchical data and vectors in one place

6. Production Best Practices

  • Consistent Similarity Thresholds: Different vector stores normalize similarity scores slightly differently (for example, pgvector and MongoDB return cosine similarity scores in [0, 1], while Redis converts cosine distance via 1 - distance). Always recalibrate similarityThreshold values if migrating between stores.

  • Deterministic Document IDs for Idempotency: Derive deterministic UUIDs from business keys (such as document hashes or database primary keys) so re-running ingestion pipelines updates existing records cleanly instead of creating duplicate vector entries.

  • Multi-Store Profiles: When running multiple vector store starters on the classpath (e.g., Redis for local testing and pgvector for production), control active auto-configuration cleanly using spring.ai.vectorstore.type.

Hands-on Experiment: Build an AI-Powered Knowledge Management System with PGVector, Redis and MongoDB

Aim: To store knowledge articles in MySQL, index their embeddings in PGVector, Redis and MongoDB using Spring AI, and run semantic search on each.

Description: A vector database stores embeddings and quickly finds the ones most similar to a query. Spring AI’s common VectorStore interface works with PGVector (PostgreSQL), Redis and MongoDB, so storage can change without changing application logic. It is used to hold document embeddings with metadata and run similarity searches with optional filters. This forms the storage layer behind knowledge bases, semantic search and RAG applications.

Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE, Postman. This topic also needs Docker for PGVector, Redis Stack and MongoDB Atlas Local.

Steps:

  1. Generate the project with Spring Initializr
  2. Add the Spring AI vector store dependencies
  3. Configure MySQL and the three vector databases
  4. Create the KnowledgeArticle entity and repository
  5. Create the service that builds and uses the three vector stores
  6. Create the REST controller
  7. Start the databases and run the application
  8. Test with Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven, Language: Java
  • Spring Boot: 3.5.x (Spring AI 1.1 needs 3.5.x, not 3.3.x)
  • Group: com.example, Artifact: knowledge-management-system
  • Packaging: Jar, Java 17
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, PostgreSQL Driver, Spring Data MongoDB, Transformers Embedding Model (ONNX)

Step 2: Project Structure

knowledge-management-system
├── docker-compose.yml
├── pom.xml
└── src/main
    ├── java/com/example/knowledge
    │   ├── KnowledgeManagementSystemApplication.java
    │   ├── entity/KnowledgeArticle.java
    │   ├── repository/KnowledgeArticleRepository.java
    │   ├── service/KnowledgeService.java
    │   └── controller/KnowledgeController.java
    └── resources/application.properties

Step 3: Github Link: 

Step 4: Download the application from above github link, then test the below CURD operations

POST Payloads and URLs (Postman)

1. Save and index in PGVector
POST http://localhost:8080/api/knowledge/articles?store=pgvector

json
{
  "title": "Employee Leave Policy",
  "content": "Employees get 24 paid leave days per year. Leave requests must be approved by the reporting manager at least two days in advance.",
  "category": "HR",
  "author": "Anita"
}

2. Save and index in Redis
POST http://localhost:8080/api/knowledge/articles?store=redis

json
{
  "title": "VPN Setup Guide",
  "content": "To work remotely and securely, install the corporate VPN client, sign in with your company email and enable multi-factor authentication.",
  "category": "IT",
  "author": "Ravi"
}

3. Save and index in MongoDB
POST http://localhost:8080/api/knowledge/articles?store=mongodb

json
{
  "title": "Kubernetes Deployment Guide",
  "content": "Deploy services to the cluster using Helm charts. Always run kubectl rollout status to confirm the new pods are healthy.",
  "category": "DevOps",
  "author": "Meera"
}

4. Index an existing article in another store (no body)
POST http://localhost:8080/api/knowledge/articles/2/index?store=pgvector

5. Semantic search (GET)

  • http://localhost:8080/api/knowledge/search?store=pgvector&query=how can I connect to the office network from home&topK=2
  • http://localhost:8080/api/knowledge/search?store=redis&query=how many days of holiday do I get&topK=2
  • http://localhost:8080/api/knowledge/search?store=mongodb&query=release new version of a service&topK=2

6. List and delete

  • GET http://localhost:8080/api/knowledge/articles
  • DELETE http://localhost:8080/api/knowledge/articles/1

Each search returns score, metadata (title, category, author) and text. The VPN query finds “VPN Setup Guide” even though it shares no words with it, because the match is by meaning.

Scroll to Top