Quick revision
The short answer
An EmbeddingModel turns text into a fixed-length vector, and texts with similar meaning get vectors pointing in similar directions, which we measure with cosine similarity. PgVectorStore keeps each chunk's content, JSON metadata and vector in a PostgreSQL table with the pgvector extension, usually with an HNSW index. A SearchRequest with topK(5), similarityThreshold(0.7) and filterExpression("tenant == 'acme'") embeds the query, keeps only rows whose metadata matches the filter, and returns at most the five closest chunks with a similarity of at least 0.7.
What to remember
In this answer, we saw that an EmbeddingModel maps text to a fixed-length vector and similar meanings give high cosine similarity. PgVectorStore stores content, JSON metadata and the vector in PostgreSQL with pgvector, usually under an HNSW index with a matching distance type. A SearchRequest embeds the query, filters by metadata, returns at most topK nearest chunks and drops those below the similarity threshold. Dimensions must match the model, changing models means re-embedding, and HNSW trades recall for speed through ef_search.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
An EmbeddingModel turns text into a fixed-length vector, and texts with similar meaning get vectors pointing in similar directions, which we measure with cosine similarity. PgVectorStore keeps each chunk's content, JSON metadata and vector in a PostgreSQL table with the pgvector extension, usually with an HNSW index. A SearchRequest with topK(5), similarityThreshold(0.7) and filterExpression("tenant == 'acme'") embeds the query, keeps only rows whose metadata matches the filter, and returns at most the five closest chunks with a similarity of at least 0.7.
Why this question is asked
Every RAG system rests on one idea: find the pieces of text that mean the same thing as the question, even when they use different words. Embeddings make that possible, and with pgvector we can do it in the PostgreSQL database many teams already run. Interviewers ask this question to check that we understand what a vector search actually computes and what each knob in the request does. In this answer, we will recap embeddings and cosine similarity, look at how PgVectorStore stores data, walk through one similarity search, and cover dimensions and approximate indexes.
1A Quick Recap of Embeddings
An embedding model reads a piece of text and returns a list of numbers of fixed length, for example 1,536 numbers. That list is a vector, a point in a space with 1,536 dimensions. The model is trained so that texts with similar meaning land close together. How do I reset my password and I forgot my login credentials share almost no words, but their vectors are close; How do I reset my password and Our office closes at 6 pm are far apart.
Closeness is usually measured with cosine similarity, which compares the direction of two vectors. It is 1 for the same direction, around 0 for unrelated texts. Spring AI exposes the model as EmbeddingModel.
The exact numbers depend on the model, but the pattern is what matters: related meaning gives a high score, unrelated meaning a low one.
2How PgVectorStore Stores Documents
pgvector is a PostgreSQL extension that adds a vector column type, distance operators and vector indexes. Spring AI's PgVectorStore uses it to store each Document as a row with an id, the text content, the metadata as JSON and the embedding. With initialize-schema enabled it creates the table and index for us; in production we usually create them with our own migration scripts.
Notice that the distance type and the index operator class must agree: a cosine distance search can use an index built with vector_cosine_ops, but not one built for another distance. PostgreSQL works with distance, where smaller is closer; Spring AI converts it to a similarity score for us.
3What a SearchRequest Does
Now we can read the search request piece by piece.
- Embed the querysame model as ingestion
- Apply the metadata filtertenant == 'acme'
- Find nearest vectorsHNSW index, cosine distance
- Keep at most topK5
- Drop results below threshold0.7
- Return documents with scores
6 steps in order. Play them, or step through them one at a time.
First, query: Spring AI embeds the question with the same EmbeddingModel used at ingestion. Second, filterExpression: it is translated into a condition on the JSON metadata, so only rows where tenant is acme are considered. Third, the database orders those rows by distance to the query vector and takes the closest ones; topK(5) means at most five. Fourth, similarityThreshold(0.7) drops any of them scoring below 0.7. So topK is a ceiling, not a promise, and here only three chunks were close enough.
The threshold protects the prompt from weak matches. Without it, a question nobody's documents can answer still gets five chunks, and the model may build an answer from them.
4Dimensions Must Match the Model
Each embedding model produces vectors of one fixed length, and the column is declared with that length, vector(1536) above. If we configure a model with 768 dimensions, inserts fail because the lengths differ. A subtler problem is switching to another model with the same length: inserts succeed, but the new vectors live in a different space from the old ones, so comparing them gives meaningless scores. Changing the embedding model therefore always means re-embedding every document, usually into a new table, and switching over once it is complete.
5Approximate Indexes and Their Trade-off
Comparing the query with every row is exact but slow once there are millions of rows. An HNSW index, a layered graph of neighbouring vectors, finds the nearest vectors by walking that graph, which is very fast but approximate: occasionally it misses a vector that is truly among the closest. The share of true nearest neighbours that the index returns is called recall.
pgvector lets us trade speed for recall with the hnsw.ef_search setting, the size of the candidate list during a search (40 by default). Raising it to 100 or 200 improves recall at the cost of latency. There is also a subtle interaction with filters: the index finds candidates first and the filter is applied to them, so with a very selective filter fewer than topK rows may survive; a higher ef_search, or iterative index scans in recent pgvector versions, helps. We measure recall on our own queries rather than guessing.
6Follow-up questions
Why are metadata filters important for multi-tenant data?
Because similarity knows nothing about ownership. If tenants share one table, a question from acme can be closest to a chunk from another customer, and without a filter that chunk ends up in acme's prompt and possibly in the answer. Adding the tenant filter on every search, ideally enforced centrally rather than by each caller, ensures we only search data the user may see. For strict isolation, some teams use a table or schema per tenant instead.
Cosine, Euclidean or inner product?
Use what the embedding model was designed for, usually cosine. For normalised vectors, cosine and inner product give the same ranking, and inner product is slightly cheaper to compute.
What is a good similarity threshold?
There is no universal value; scores depend on the model. We pick it from data by looking at scores of relevant and irrelevant chunks for a set of real questions.
7Conclusion
In this answer, we saw that an EmbeddingModel maps text to a fixed-length vector and similar meanings give high cosine similarity. PgVectorStore stores content, JSON metadata and the vector in PostgreSQL with pgvector, usually under an HNSW index with a matching distance type. A SearchRequest embeds the query, filters by metadata, returns at most topK nearest chunks and drops those below the similarity threshold. Dimensions must match the model, changing models means re-embedding, and HNSW trades recall for speed through ef_search.
Open with
An embedding model turns text into a fixed-length vector, say 1,536 floats, trained so that similar meanings give vectors in similar directions, which we compare with cosine similarity.
Then, if they want more
In Spring AI that is the EmbeddingModel. PgVectorStore uses PostgreSQL with the pgvector extension: each chunk is a row with id, content, JSON metadata and a vector column, typically with an HNSW index and cosine distance, configured with spring.ai.vectorstore.pgvector properties.
When I call similaritySearch with a SearchRequest, Spring AI embeds the query with the same model, applies the filter expression, for example tenant == 'acme', as a condition on the metadata, asks the database for the nearest vectors, keeps at most topK, say five, and drops any with similarity below the threshold, say 0.7.
So topK is a maximum, and the threshold stops weak matches from reaching the prompt. The filter is essential for multi-tenant data, because similarity does not know who owns a chunk. The vector dimensions must match the model, and if we change the model we must re-embed everything.
HNSW is approximate, so I would tune hnsw.ef_search for recall against latency and measure recall on real queries.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring AI reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain how embeddings and vector similarity search work in Spring AI with PGvector....": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/f7de4e32f7/