1. Core Concepts: Embeddings & Semantic Search
-
What is an Embedding? An embedding is a dense, fixed-length array of floating-point numbers (a vector) that represents the semantic characteristics of a piece of text, image, or document. Regardless of whether the input is a two-word phrase or a multi-sentence paragraph, a given embedding model outputs a vector of a fixed dimensionality (e.g., 768 dimensions for Ollama’s
nomic-embed-textor 1,536 dimensions for OpenAI’stext-embedding-3-small). -
Semantic Similarity vs. Keyword Search: Traditional relational databases and lexical search engines look for exact character or word overlaps (e.g., SQL
LIKEor BM25). In contrast, embedding models map conceptually related inputs close together in a high-dimensional vector space. For example, a query for “space movie” will sit geometrically close to a document describing “astronauts traveling through a wormhole”, even though they share zero identical keywords. -
Distance & Similarity Metrics: Vector databases measure closeness between query vectors and stored document vectors using mathematical distance functions—most commonly Cosine Similarity, Euclidean Distance (L2), and Dot Product.
2. The EmbeddingModel Abstraction
EmbeddingModel interface (extending Spring AI’s foundational Model API).Architectural Goals & Components
-
Portability & Simplicity: Application services inject
EmbeddingModelwithout coupling business logic to vendor SDKs. Switching from a cloud embedding API to a local model requires changing only Maven/Gradle starter dependencies and configuration properties. -
Core Operations: Supports embedding single strings, batches of strings (for high-throughput ingestion), or structured Spring AI
Documentobjects. -
Request & Response Lifecycle:
-
EmbeddingRequest: Wraps input texts alongside runtimeEmbeddingOptions(such as model overrides or output dimension truncation). -
EmbeddingResponse: Returns a list ofEmbeddingobjects (each holding itsfloat[]vector and batch index) along withEmbeddingResponseMetadatacontaining token usage statistics and provider metadata.
-
-
Supported Embedding Providers: OpenAI, Google GenAI & Vertex AI Text/Multimodal Embeddings, Ollama (local open-weight models like
nomic-embed-textormxbai-embed-large), Amazon Bedrock (Titan, Cohere), Azure OpenAI, Mistral AI, Hugging Face, and in-process ONNX Transformers (running models directly inside the JVM without external APIs).
3. Vector Stores & The VectorStore API
VectorStore interface (and its read-only counterpart, VectorStoreRetriever).Key Responsibilities
-
Automatic Embedding on Write & Read: When documents are added via
VectorStore.add(), Spring AI automatically invokes the configuredEmbeddingModelbehind the scenes to compute vectors before persisting both the text, metadata, and vector payload. Similarly, when querying with a raw text string,VectorStoreembeds the query string automatically before executing the similarity search. -
Supported Vector Databases: PostgreSQL (
pgvector), Redis, MongoDB Atlas, Elasticsearch, Pinecone, Weaviate, Qdrant, Milvus, Chroma, Neo4j, and Apache Cassandra. -
Schema & Index Initialization: Many Spring AI vector store starters support automatic schema initialization (
initialize-schema=true) and specialized vector indexing algorithms such as HNSW (Hierarchical Navigable Small World) and IVFFlat to ensure sub-second retrieval at scale.
4. Semantic Search Workflow & Query Capabilities
Stage 1: Data Ingestion (Indexing)
-
Raw enterprise documents (PDFs, Markdown, HTML, JSON, database records) are parsed into Spring AI
Documentobjects. -
Large documents are split into smaller, semantically coherent chunks (using token-based or character-based text splitters) and enriched with key-value metadata (e.g., author, department, timestamp, document category).
-
Chunks are passed to
VectorStore, which generates embeddings and stores them in the vector index.
Stage 2: Retrieval (SearchRequest)
VectorStore.similaritySearch() configured via a SearchRequest builder:-
Query String: The natural-language search input from the user.
-
Top-K (
topK): Limits the maximum number of closest matching document chunks returned (e.g., top 5 results). -
Similarity Threshold (
similarityThreshold): A score filter between0.0and1.0that discards weak or unrelated matches so irrelevant noise is never returned. -
Portable Metadata Filtering (
filterExpression): Combines semantic vector search with deterministic SQL-like metadata filters (e.g.,category == 'finance' && year >= 2025), which Spring AI translates natively into each vector database’s underlying query syntax.
5. Production Best Practices
-
Match Vector Dimensions Strictly: The column or index dimension configured in your vector database must match the exact output dimension of your chosen
EmbeddingModel(e.g., 768 vs. 1536); changing embedding models requires re-indexing existing documents. -
Optimize Chunking Strategy: Overly large chunks dilute vector precision across too many topics, while overly tiny chunks lose surrounding context; tuning chunk size and overlap directly impacts search relevance.
-
Combine Semantic & Metadata Filtering: Always attach tenant IDs, user permissions, or domain tags as document metadata so semantic searches remain fast, scoped, and secure.
-
Foundation for RAG: Semantic search serves as the retrieval engine for Retrieval-Augmented Generation (RAG)—feeding the top-K retrieved
Documentchunks into aChatClientprompt so LLMs answer questions grounded in private, up-to-date enterprise data.
Hands-on Experiment: Intelligent Product Search Engine using Spring AI Embeddings
Aim: To build a Spring Boot application that converts product details into embeddings using Spring AI and finds products by meaning with semantic search.
Description: An embedding model turns text into a numeric vector that represents its meaning. Texts with similar meaning have vectors that sit close together, which allows search by meaning rather than exact keywords. Spring AI provides the EmbeddingModel abstraction to generate these vectors from any supported provider. It is used for semantic search, recommendations and finding related content, such as matching a shopper’s query to relevant products.
Software / Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman, and an OpenAI API key.
Steps:
- Generate the project with Spring Initializr
- Create the project structure
- Configure
pom.xmlandapplication.properties - Create the entity, repository, service and controller
- Run the application and load sample products
- Compare keyword search with semantic search
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven | Language: Java | Packaging: Jar | Java: 17
- Spring Boot: 3.4.x (Spring AI 1.0 needs 3.4 or higher)
- Group:
com.example| Artifact:product-search - Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI
Step 2: Project Structure
product-search
├── pom.xml
└── src/main
├── java/com/example/productsearch
│ ├── ProductSearchApplication.java
│ ├── entity (Product)
│ ├── repository (ProductRepository)
│ ├── service (ProductSearchService)
│ └── controller (ProductSearchController)
└── 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. Load sample products (one embedding request)POST http://localhost:8080/api/products/bulk
[
{"name": "Steel Insulated Water Bottle", "description": "Double wall flask that keeps drinks cold for 24 hours and hot for 12 hours", "category": "Kitchen", "price": 899},
{"name": "Noise Cancelling Headphones", "description": "Wireless over-ear headphones with deep bass and 30 hour battery", "category": "Electronics", "price": 7999},
{"name": "Running Shoes", "description": "Lightweight breathable shoes with cushioned sole for jogging and marathons", "category": "Sports", "price": 3499},
{"name": "Ergonomic Office Chair", "description": "Adjustable chair with lumbar support for long working hours", "category": "Furniture", "price": 6499},
{"name": "Yoga Mat", "description": "Non-slip thick mat for yoga, stretching and home workouts", "category": "Sports", "price": 799},
{"name": "Mechanical Keyboard", "description": "Backlit keyboard with tactile switches for typing and gaming", "category": "Electronics", "price": 2999},
{"name": "Cast Iron Skillet", "description": "Heavy pan for frying, searing and baking on stove or oven", "category": "Kitchen", "price": 1499},
{"name": "Smart Fitness Band", "description": "Wrist band that tracks steps, heart rate and sleep", "category": "Electronics", "price": 1999}
]
2. Add one productPOST http://localhost:8080/api/products
{ "name": "Laptop Stand", "description": "Foldable aluminium stand to raise your laptop", "category": "Electronics", "price": 999 }
3. See what an embedding looks likePOST http://localhost:8080/api/products/embed
{ "text": "wireless headphones" }
4. Compare two textsPOST http://localhost:8080/api/products/similarity
{ "textA": "cheap laptop", "textB": "affordable notebook computer" }
5. Semantic search: GET http://localhost:8080/api/products/search/semantic?query=something to keep my drinks cold&topK=3
6. Keyword search (finds nothing for the same query): GET http://localhost:8080/api/products/search/keyword?q=something to keep my drinks cold
7. Another semantic search: GET http://localhost:8080/api/products/search/semantic?query=gear for staying fit at home
8. All products: GET http://localhost:8080/api/products
Search compares the query with every product in Java, which works for hundreds or a few thousand products. For very large catalogs, use a vector store such as PGvector, Redis or Chroma, which Spring AI supports in a later topic.
