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
-
Automatic Embedding Pipeline: Whenever documents are added (
add) or queried via natural language (similaritySearch), theVectorStoreautomatically invokes the configuredEmbeddingModelto compute vector arrays before executing database operations. (For pre-computed vectors,upsertis also supported.) -
Token-Aware Batching (
BatchingStrategy): Before sending large document sets to an embedding provider, Spring AI usesTokenCountBatchingStrategyto 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 (SQLWHEREclauses, 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-pgvectorand reuses Spring Boot’s standardJdbcTemplateand PostgreSQLDataSource. -
Storage Layout: Persists records inside a relational table (defaulting to
public.vector_store) with columns for document UUIDs, text content, JSONB metadata, and thevectorembedding 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)
-
Starter & Integration: Uses
spring-ai-starter-vector-store-redisbacked by Jedis and Spring Data Redis connection properties. -
Storage Layout: Stores each Spring AI
Documentas 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, orTEXTfields) 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)
mongot), allowing operational JSON documents and vector embeddings to live in the same collection.-
Starter & Integration: Uses
spring-ai-starter-vector-store-mongodb-atlasbuilt on top ofMongoTemplateand Spring Data MongoDB. -
Storage Layout: Stores each Spring AI
Documentas 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
$vectorSearchaggregation pipeline stage powered by Apache Lucene HNSW indexes. -
Supports pre-filtering metadata fields directly inside the
$vectorSearchstage for high-efficiency scoped queries. -
When
spring.ai.vectorstore.mongodb.initialize-schema=trueis 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,
pgvectorand MongoDB return cosine similarity scores in[0, 1], while Redis converts cosine distance via1 - distance). Always recalibratesimilarityThresholdvalues 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
pgvectorfor production), control active auto-configuration cleanly usingspring.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:
- Generate the project with Spring Initializr
- Add the Spring AI vector store dependencies
- Configure MySQL and the three vector databases
- Create the
KnowledgeArticleentity and repository - Create the service that builds and uses the three vector stores
- Create the REST controller
- Start the databases and run the application
- 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 PGVectorPOST http://localhost:8080/api/knowledge/articles?store=pgvector
{
"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 RedisPOST http://localhost:8080/api/knowledge/articles?store=redis
{
"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 MongoDBPOST http://localhost:8080/api/knowledge/articles?store=mongodb
{
"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=2http://localhost:8080/api/knowledge/search?store=redis&query=how many days of holiday do I get&topK=2http://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/articlesDELETE 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.
