Traditional search matches words. If a user types "reset my password" and your help article is titled "Recovering account access", keyword search may never connect the two. Vector search can, because it compares meaning rather than spelling.
Embeddings and vector search sit underneath almost every serious AI application today, from retrieval augmented generation to recommendation engines and duplicate detection. This guide explains how they work and how to use them well, with the details that tutorials usually skip.
What an embedding is
An embedding is a list of numbers, a vector, that represents the meaning of a piece of text. An embedding model takes text in and returns a vector with a fixed number of dimensions, commonly somewhere between a few hundred and a few thousand.
The key property is simple: texts with similar meanings produce vectors that are close together. "How do I reset my password" and "I forgot my login credentials" end up near each other. "Best mango varieties in Uttar Pradesh" ends up far away.
The individual numbers do not have human-readable meanings. What matters is the geometry, the distances and directions between vectors.
Where embeddings come from
Embedding models are neural networks trained so that related texts land close together. Training often uses pairs of texts that should match, such as a question and its answer, and pushes them together while pushing unrelated texts apart.
You can get embeddings from:
- hosted APIs from providers such as OpenAI, Google, Cohere and Voyage AI (Anthropic's documentation recommends Voyage AI for embeddings, as Anthropic does not offer its own embedding model)
- open-source models you run yourself, many of which are listed on public embedding leaderboards
- cloud platforms such as Azure, AWS and Google Cloud, which bundle embedding models with their AI services
Choose based on quality for your language and domain, cost, latency, data privacy requirements and whether you need to run offline.
Measuring similarity
Once you have vectors, you need a way to compare them. The three common measures are:
- Cosine similarity: compares the angle between vectors, ignoring length. Values range from minus one to one, with higher meaning more similar. This is the most common choice for text.
- Dot product: similar to cosine when vectors are normalised to length one, and slightly faster.
- Euclidean distance: the straight-line distance. Smaller means more similar.
Many embedding models return normalised vectors, in which case cosine similarity and dot product give the same ranking. Check your model's documentation and use the metric it recommends.
A minimal cosine similarity function in Python looks like this:
import numpy as np
def cosine(a, b):
a, b = np.array(a), np.array(b)
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
The basic vector search flow
Every vector search system follows the same pattern.
Indexing
1. Split your documents into chunks.
2. Send each chunk to the embedding model.
3. Store each vector along with the original text and metadata such as source, date and category.
Querying
1. Embed the user's query with the same model.
2. Find the stored vectors closest to the query vector.
3. Return the matching chunks, usually the top 5 to 20.
The rule that catches beginners: always use the same embedding model for documents and queries. Vectors from different models live in different spaces and cannot be compared. If you switch models, you must re-embed everything.
Chunking is where quality is won or lost
Embedding an entire 50-page document as one vector blurs its meaning into an average. Embedding single sentences loses context. Chunking strategy has a bigger effect on retrieval quality than most teams expect.
Common approaches:
- Fixed size: split every few hundred tokens with some overlap, for example 400 tokens with 50 tokens of overlap. Simple and predictable.
- Structure-aware: split on headings, paragraphs or sections. Works well for documentation and articles.
- Semantic: split where the topic changes, detected by embedding similarity between neighbouring sentences.
- Code-aware: split source files by function or class rather than by line count.
Practical tips:
- Include the document title and section heading in each chunk's text. A chunk that says "Set the timeout to 30 seconds" is far more useful when it also says which product and which setting.
- Keep chunks small enough to be specific but large enough to stand alone.
- Store a pointer back to the full document so you can show sources or expand context.
Anthropic has published a technique it calls contextual retrieval, where a short, model-generated description of how each chunk fits into its document is added before embedding. Their published results showed a meaningful reduction in retrieval failures. It costs extra processing at indexing time but is worth testing for important knowledge bases.
Scaling with approximate nearest neighbour search
Comparing a query against every stored vector, known as brute force or exact search, works fine for thousands or even a few hundred thousand vectors. Beyond that, it gets slow.
Vector databases use approximate nearest neighbour (ANN) algorithms that trade a tiny amount of accuracy for huge speed gains:
- HNSW (Hierarchical Navigable Small World): builds a layered graph where each vector links to its neighbours. Search starts at the top layer and quickly narrows down. Fast and accurate, but memory-hungry. The most popular choice today.
- IVF (Inverted File Index): groups vectors into clusters and searches only the most promising clusters.
- Product quantisation: compresses vectors to save memory, often combined with IVF.
Most of these have tuning parameters that balance speed, memory and recall. Start with defaults and tune only after you measure.
Where to store vectors
Options fall into a few groups:
- Dedicated vector databases such as Pinecone, Weaviate, Qdrant, Milvus and Chroma.
- Extensions to existing databases, such as pgvector for PostgreSQL, and vector features in SQL Server, MongoDB Atlas, Elasticsearch, OpenSearch and Redis.
- Cloud search services such as Azure AI Search, which combine vector and keyword search with enterprise features.
- Libraries such as FAISS for in-process search.
If you already run PostgreSQL or SQL Server, adding vector search there is often the simplest start. Our article on choosing a vector database compares the options in detail.
Hybrid search beats pure vector search
Vector search is great at meaning but weak at exact matches. Search for an error code like "0x80070005", a product SKU or a person's name, and semantic similarity may return conceptually related but wrong results.
Keyword search, typically using the BM25 ranking algorithm, is the opposite: precise on exact terms, blind to synonyms.
Hybrid search runs both and merges the results. A popular merging method is reciprocal rank fusion, which scores each result based on its position in each list. Hybrid search consistently outperforms either method alone in real-world tests, and most modern vector databases support it directly.
Re-ranking for precision
Vector search is fast because it compares precomputed vectors. But it never looks at the query and document together. A re-ranker, often called a cross-encoder, takes the query and each candidate passage as a pair and scores how well they match.
The usual pattern:
1. Retrieve the top 50 to 100 candidates with hybrid search.
2. Re-rank them with a cross-encoder model.
3. Keep the top 5 to 10 for the final result or for the LLM prompt.
Re-ranking adds some latency and cost, but often gives the biggest quality jump of any single change.
Metadata filtering
Real applications need filters: only documents this user can access, only the latest product version, only content in Hindi. Store metadata alongside each vector and apply filters during search.
Access control filters are especially important. Never rely on the LLM to hide documents a user should not see. Filter them out at the retrieval layer.
Measuring retrieval quality
You cannot improve what you do not measure. Build a small evaluation set of 50 to 200 real queries with the documents that should be returned. Then track:
- Recall at K: did the right document appear in the top K results?
- Mean reciprocal rank: how high did the first correct result rank?
- Precision: how many of the returned results were relevant?
Run this evaluation whenever you change chunking, embedding models, search settings or re-rankers.
Common mistakes
- Using different embedding models for indexing and querying.
- Chunks that lack context, such as missing titles or headings.
- Relying on vector search alone for codes, IDs and names.
- Never re-embedding after changing the model.
- Skipping evaluation and judging quality by a few manual tests.
- Ignoring access control at the retrieval layer.
- Storing vectors without the original text, making debugging painful.
Beyond text
Embeddings are not limited to text. Multimodal models can embed images and text into the same space, so a text query can find matching photos. Code embeddings power semantic code search. Embeddings of user behaviour drive recommendations. The same principles of distance, indexing and evaluation apply.
Key takeaways
- Embeddings turn meaning into geometry.
- Use the same model for documents and queries.
- Chunking quality drives retrieval quality.
- Hybrid search plus re-ranking beats vector search alone.
- Filter for permissions at retrieval time.
- Measure with a real evaluation set.
Master these fundamentals and you have the foundation for retrieval augmented generation, semantic search, recommendations and much more.
Related articles on MindStick
- Retrieval Augmented Generation From Scratch, A Practical Architecture
- Choosing a Vector Database, Options and Trade-offs
- Azure AI Search for Building Enterprise RAG
- How Large Language Models Actually Work, From Tokens to Answers
Model names, provider offerings and database features change often. Verify current options and pricing with each vendor before making production decisions.
Leave a Comment