A customer writes to support: “my card was charged twice”. Your help centre has the perfect article, titled “Duplicate payment: how to get a refund”. The two texts share no important word, so an ordinary search box finds nothing.
A person sees at once that they are about the same thing. How do you get a computer to see it? That is the question embeddings and vector databases answer. In one sentence: embeddings let a computer compare texts by meaning, and a vector database finds the closest matches quickly, even among millions of texts. Together they are the search engine behind many “chat with your documents” tools. This post explains both, assuming you have never met either.
First, the words
These are the only terms you need to follow this post. Each one is explained again where it first appears.
- Model — a program that learned patterns from a huge number of examples and now produces an output for an input.
- Training — showing a model a huge number of examples so that it adjusts its internal numbers and learns the patterns.
- Embedding — a list of numbers that represents the meaning of a piece of text, so that similar meanings get similar numbers.
- Vector — simply a list of numbers; in this post it means the same thing as an embedding.
- Embedding model — the model that reads a text and returns its embedding.
- Keyword search — ordinary search that finds texts containing the same words you typed.
- Semantic search — search by meaning, which finds texts about the same thing even when the words differ.
- Vector database — a database that stores embeddings and quickly finds the ones closest to a new one.
The short answer
An embedding is a list of numbers that represents the meaning of a piece of text. A vector database stores those lists and can quickly find the ones closest to a new one.
The analogy I’ll use all the way through: a map. Every text gets coordinates, the way every town has a latitude and longitude. Texts with similar meaning are placed close together, like neighbouring towns. Searching becomes “put a pin where the question lands and look at what is nearby”.
Why it exists
Computers are very good at comparing characters. Is this string (a piece of text, as a computer stores it) equal to that string? Does this document contain this word? Classic search, usually called keyword search, is built on that ability.
The trouble is that people do not repeat the words of the document they need. They say “charged twice” when the article says “duplicate payment”. They say “can’t get in” when the article says “login issues”. They ask in Ukrainian when the article is in English. Same meaning, different characters, and keyword search comes back empty or, worse, returns something that shares a word but not the topic (“Update your card details”).
A common older fix was to patch this by hand with synonym lists: “charged twice = duplicate payment = double billing”. That works for ten phrases. It does not work for everything a customer might type.
Embeddings solve the problem at the root. Instead of comparing characters, you compare positions on the map of meaning. And once you have millions of positions, you need a fast way to find the nearest ones, which is the job of a vector database.
This is also what sits underneath RAG (retrieval-augmented generation), the technique of looking up relevant documents and handing them to a language model (the kind of AI behind chat assistants, which writes text) before it answers. If you want to see where embeddings are used in a full system, read RAG explained for beginners after this post.
How it works, step by step
Our running example is a small help centre with seven articles (invented for this post):
- Duplicate payment: how to get a refund
- Refund timelines by payment method
- Error PAY-402 explained
- Update your card details
- Reset your password
- Can’t log in after changing your email
- Track your delivery
The customer’s query is “my card was charged twice”.
Step 1. Turn each text into numbers
An embedding model is a neural network (a program built from many layers of simple calculations) that was trained on a huge amount of text, and it has one narrow job: you give it text, it returns a fixed-length list of numbers. That list is the embedding. Programmers call a list of numbers a vector, so “embedding” and “vector” are used almost interchangeably. (In real systems a “piece of text” is usually a passage of a paragraph or two, called a chunk; the RAG post explains why.)
To make this visible, pretend the model returns only two numbers per text. This is a toy: I chose the numbers by hand so they are easy to read.
| Text | Number 1 | Number 2 |
|---|---|---|
| Duplicate payment: how to get a refund | 0.80 | 0.30 |
| Reset your password | 0.10 | 0.90 |
| Query: “my card was charged twice” | 0.90 | 0.20 |
With two numbers you can draw each text as a point on paper. In this toy, the first number happens to behave like “how much this is about money” and the second like “how much this is about account access”. The query lands next to the payment article and far from the password article.
Now the real picture. A real embedding has hundreds or thousands of numbers, called dimensions. As examples, OpenAI, one of the companies that sell embedding models, lists 1,536 dimensions for one of its models and 3,072 for another in its documentation (source), and most of the current models from Voyage AI, another such company, default to 1,024 (source). Nobody can draw a 1,024-dimensional map, and the individual numbers do not have tidy labels like “money”. The model learned them on its own during training. What carries over from the toy is the one property that matters: similar meaning ends up at nearby points.
Why does that work at all? The model was trained on enormous numbers of text pairs and was rewarded for putting related texts close together and unrelated ones far apart. It never received a rule saying “charged twice means duplicate payment”. It absorbed that from how people write.
A quick detour: tokens are not embeddings
These two words get mixed up constantly, so let’s separate them.
A token is a small piece of text, a word or part of a word, that a model reads. Splitting text into tokens is like cutting a sentence into puzzle pieces. Tokens say nothing about meaning; they are just the units a model counts and bills by. (More on that in token economics.)
An embedding, in the sense used in search, is one vector for a whole piece of text: a sentence, a paragraph, an article. It is the result that comes out after the model has read all the tokens. (Inside a language model each token also gets a vector of its own, and that is called an embedding too. This post is about the one-vector-per-text kind.)
So: text is cut into tokens, the embedding model reads the tokens, and one vector comes out. Tokens are the input units. The embedding is the output.
Step 2. Measure how close two vectors are
We need a number that says “how similar are these two points”. The most common choice is cosine similarity.
Forget the name for a moment. Picture each vector as an arrow from the centre of the map to its point. Cosine similarity only asks: do the two arrows point in the same direction? Same direction gives a score near 1. Unrelated directions give a score near 0. Opposite directions give a negative score.
With our toy vectors, the query and “Duplicate payment” score about 0.99, and the query and “Reset your password” score about 0.32. 0.99 against 0.32: the payment article wins by a wide margin, without a single shared keyword.
Optional: the arithmetic. You can skip this box; nothing later depends on it.
The recipe has three moves: multiply the matching numbers, add the results, then divide by the lengths of the two arrows. The length of an arrow comes from Pythagoras: square each number, add the squares, take the square root. For the query, √(0.90² + 0.20²) ≈ 0.92.
- Query (0.90, 0.20) and “Duplicate payment” (0.80, 0.30): 0.90 × 0.80 + 0.20 × 0.30 = 0.78. Divide by the two lengths (about 0.92 and 0.85) and you get roughly 0.99.
- Query (0.90, 0.20) and “Reset your password” (0.10, 0.90): 0.90 × 0.10 + 0.20 × 0.90 = 0.27. Divide by the lengths (about 0.92 and 0.91) and you get roughly 0.32.
With 1,024 numbers instead of two, the arithmetic is exactly the same, just longer.
Why direction and not plain distance? Because the length of the arrow tends to carry things you don’t care about, while the direction carries the topic. In practice the difference is often small: many providers (the companies that offer embedding models) return vectors already scaled to length 1, so every arrow has the same length. For such vectors cosine similarity, the simpler “dot product” (the first two moves without the division) and ordinary straight-line distance all rank results in the same order. Both the OpenAI and the Voyage AI documentation linked above say this about their own models.
One warning: the score is useful for ranking within one model. A 0.82 from one model and a 0.82 from another do not mean the same thing, and there is no universal threshold for “relevant”.
Step 3. Combine with keyword search
Search by meaning, which is what we have built so far, is called semantic search. It has a blind spot, and it is the mirror image of keyword search.
Suppose the customer writes: “card charged twice, error PAY-402”. The code PAY-402 is not a concept. It is an arbitrary label. An embedding model has little to hold on to, so the article “Error PAY-402 explained” may not rank near the top. Keyword search finds it instantly, because the exact string is right there. The same applies to order numbers, product codes (SKUs), surnames, function names and legal clause numbers.
So systems in production (used by real customers) often run both and merge the two result lists. This is hybrid search. A common merging method is reciprocal rank fusion: each document gets points based on its position in each list, and the points are added, so a document ranked well by either method rises (Elastic’s description). You do not need to compare a keyword score with a cosine score, which are on unrelated scales. Only the positions matter.
(The outcomes in the diagram are illustrative. Real models catch some codes some of the time. The point is that you should not rely on it.)
Keyword, semantic and hybrid search side by side
| Keyword search | Semantic (vector) search | Hybrid search | |
|---|---|---|---|
| Matches on | The same words | Similar meaning | Both |
| “charged twice” finds “duplicate payment” | No | Yes | Yes |
Finds exact code PAY-402 | Yes, reliably | Not reliably | Yes |
| Works across languages | No | Yes, with a multilingual model | Yes, for the semantic half |
| Needs an embedding model | No | Yes | Yes |
| Easy to explain why a result appeared | Yes, the word is there | Harder, it is a score | Mixed |
| Typical use | IDs, names, codes, logs (records of what a system did) | Questions in natural language | General-purpose search and RAG |
Going further: large collections
This part is for when you build a real system with many thousands of texts. If this is your first read, you can skip to “Common mistakes and misconceptions” and come back later.
Finding the nearest points fast
Finding the closest vectors to a query is called nearest-neighbour search. With seven articles you just compare the query with all seven. That brute-force approach (checking every single item) is exact and perfectly fine for small collections.
Now imagine ten million articles stored in a database (a program that stores data and answers questions about it). A database keeps each article as a row, one record with an id number and other fields, and uses an index, a prepared lookup structure, to find rows without reading them all. An ordinary index does not help here. It is like an alphabetical phone book: superb for “find the row where id = 4182”, useless for “find the rows whose 1,024 numbers are closest to these 1,024 numbers”. There is no alphabetical order for closeness in a thousand dimensions, so without something smarter the database has to compare the query with every single row.
The something smarter is approximate nearest neighbour search, or ANN. The deal is simple: accept that once in a while you will miss one true neighbour, and in exchange search a tiny fraction of the data.
One of the most widely used ANN indexes is HNSW (Hierarchical Navigable Small World), introduced in a 2016 paper by Malkov and Yashunin. Back to the map: to drive to a small village you do not check every road in the country. You take a motorway to the right region, a regional road to the right district, then local streets. HNSW builds exactly that: several layers of links between points, with a few long-range links on top and many short ones at the bottom. A search starts at the top, keeps moving to whichever linked point is closer to the query, and drops a layer each time it cannot get closer.
This is where the speed versus accuracy trade-off lives. Every ANN index has settings that mean “look harder”. Looking harder finds more of the true neighbours (engineers call that share recall) but takes longer. You tune it to what your application can tolerate. For a help-centre search, missing the seventh-best article now and then is invisible. For finding duplicate legal records, it may not be.
Filtering by metadata
Meaning is not the only thing you search by. The customer is on the mobile app, speaks English, and should not see internal-only articles. So next to each vector you store metadata: plain fields such as language, product, visibility, updated_at.
A query then becomes “the nearest neighbours to this vector where language = ‘en’ and visibility = ‘public’”. On the map: only look at pins of a certain colour.
It sounds trivial, and it hides a real trap. If the database finds the ten nearest points first and filters afterwards, and eight of them are in the wrong language, you get two results instead of ten. The documentation of pgvector, an add-on that gives the PostgreSQL database vector search (more on it in the next section), describes this behaviour for approximate (ANN) indexes and offers “iterative scans” that keep searching until enough rows pass the filter. Other vector databases apply the filter during the search itself. When you evaluate any of them, check how it handles filters, especially strict ones.
Metadata is also your security boundary. “This user may only see their own company’s documents” must be a filter enforced by your code, never something you hope the similarity score will sort out.
Where do the vectors live?
A vector database is any system that stores vectors together with their metadata and answers nearest-neighbour queries using an ANN index. There are two broad ways to get one.
| Dedicated vector database | Vector support in a database you already run | |
|---|---|---|
| Examples | Pinecone, Qdrant, Weaviate, Milvus, Chroma | PostgreSQL (often called Postgres) with the pgvector extension; also Elasticsearch, OpenSearch, MongoDB, Redis |
| What you gain | Built around vector search from day one; features and tuning for very large collections | One system to run, back up and secure; vectors sit next to your ordinary rows; joins (combining rows from several tables) and transactions (changes that succeed or fail together) keep working |
| What it costs | One more service to operate and keep in sync with your main data | Vector search shares resources with everything else; you tune it yourself |
Neither column is “the right one”. If your application already uses Postgres and you have a modest number of vectors, adding pgvector is a reasonable start: it does exact search by default and lets you add an HNSW index when you need speed. If vector search is the core of your product at very large scale, a dedicated engine may be the better fit. Decide on your data size, your filters and your team’s operational habits, not on a leaderboard (a public ranking of products by benchmark scores).
Common mistakes and misconceptions
- Embedding documents with one model and queries with another. Each model draws its own map. Coordinates from one map are meaningless on another, and nothing will stop with an error message; you will just get confident nonsense. Some models also want to be told whether the text is a document or a query; Voyage AI’s
input_typesetting is one example. Read your model’s documentation. - Changing the model and keeping the old vectors. A new model, or even a new version, means a new map. You must re-embed the whole collection. Plan for it: store the model name with every vector and keep the original text.
- Ignoring dimensions and storage. More dimensions means more disk, more memory and slower search. pgvector’s documentation gives the size of one stored vector as 4 × dimensions + 8 bytes. By that formula a 1,536-dimension vector takes about 6 KB (kilobytes), so a million of them take roughly 6 GB (gigabytes) before any index. Some models let you request shorter vectors to trade a little quality for a lot of space.
- Assuming any model handles any language. Some models are trained mainly on English. If your users write in Ukrainian or Georgian, pick a model documented as multilingual (trained on many languages) and test it on your own texts.
- Treating the similarity score as truth. Nearest does not mean relevant. If nothing in the collection answers the question, the search still returns the “closest” items. A later step, such as the language model or a check you write, has to judge whether they are good enough.
- Embedding whole long documents as one vector. One point cannot represent fifty pages on ten topics, and models have input limits. Documents are split into smaller pieces called chunks first. The RAG post covers how.
When you don’t need it
- Your collection is small. A few thousand vectors can be compared by brute force in memory in a few lines of Python. That is exact, simple, and often fast enough. No database required.
- People search by exact identifiers. Order numbers, emails, error codes, file names. Keyword search or a plain database query is faster, cheaper and easier to explain.
- Everything fits in the model’s context. The context window is the amount of text a model can take in at once. If the whole knowledge base is a few pages, you can simply give all of it to the language model with the question. Context engineering, deciding what goes into the model’s input, matters more there than retrieval (the “find the relevant passages” step).
- Your existing search is good enough. If users find what they need with the current full-text search (keyword search over whole documents), embeddings add cost and a moving part. Measure first; evals, repeatable tests with fixed inputs and expected results, are how you find out.
How to get there
A learning order I’d suggest for a beginner:
- Basic Python (a programming language). Lists, loops, functions, calling an API (a service your program sends requests to). That is all the programming this topic needs at first.
- Embed ten sentences by hand. Pick any embedding API or open model (one you can download and run yourself), embed ten sentences you wrote yourself, and print the cosine similarity between each pair. Seeing “charged twice” score high against “duplicate payment” makes everything above concrete.
- Build brute-force search. Take 100 to 200 short texts (FAQ entries, recipe titles, your own notes), embed them, store the vectors in a list, and write a function that returns the top five for a query. No database yet.
- Move it into a real store. Load the same data into Postgres with pgvector or any dedicated vector database. Add an index. Compare the results with your brute-force version: that comparison is recall.
- Add metadata and a filter. Tag each text with a category and language, then search within one category.
- Add keyword search and merge. Run both on queries that contain an exact code, and watch hybrid search fix what each one misses.
- Plug it into RAG. Hand the retrieved texts to a language model and let it answer. At this point you have built the core of many “chat with your documents” products.
Keep a list of twenty test queries with the answers you expect. Rerun it after every change. It is the cheapest habit that separates guessing from engineering.
Mini glossary
- Embedding — a list of numbers representing the meaning of a piece of text (or an image, or audio).
- Vector — a list of numbers; in this context, a synonym for embedding.
- Dimension — one number in the vector; real embeddings have hundreds or thousands.
- Embedding model — the neural network that turns text into an embedding.
- Token — a small piece of text a model reads; the input unit, not the meaning.
- Cosine similarity — a score for how closely two vectors point in the same direction.
- Nearest-neighbour search — finding the stored vectors closest to a query vector.
- ANN (approximate nearest neighbour) — a faster search that may occasionally miss a true neighbour.
- HNSW — a popular ANN index built as layers of links between points.
- Recall — the share of true nearest neighbours the search actually returned.
- Hybrid search — keyword and semantic search run together, with merged results.
Going deeper
Courses that take you from this post to working systems:
- Python Fundamentals — the starting point if you have not programmed before.
- Prompt Engineering & AI Workflow Automation — how to work with language models before you add retrieval.
- Building LLM-Powered Apps: RAG & Agents — embeddings, vector stores and retrieval in a complete application.
- Building with Claude API — calling a model from your own code, including with retrieved context.
- AWS Bedrock & AI Services for Developers — running embedding models and vector search on managed cloud services.
Related posts in this series:
- RAG explained for beginners — where embeddings and vector search are put to work.
- The layers of an AI system — where retrieval fits in the whole stack.
- Types of AI models explained — how embedding models differ from chat models.
- The AI Engineer Roadmap — the full learning path this topic belongs to.
Sources and further reading
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs — the original HNSW paper (Malkov, Yashunin).
- pgvector README — index types, exact versus approximate search, filtering, storage sizes.
- OpenAI embeddings guide — definitions, dimensions, shortening vectors, distance functions.
- Embeddings in the Claude documentation — query versus document input types, normalised vectors, quantization.
- Reciprocal rank fusion in the Elasticsearch reference — how keyword and semantic result lists are merged.
- Hierarchical Navigable Small Worlds (Pinecone learning series) — a longer walkthrough of HNSW and its parameters.
This post is part of the “AI engineering from zero” series: The AI engineer roadmap · Vibe coder vs AI engineer vs AI solutions engineer · 8 types of AI models · RAG explained for beginners · AI agents and tool calling · The 7 layers of an AI system.
Part 4 of 7 in “AI engineering from zero”. Previous: 8 Types of AI Models Explained From Zero: LLM, SLM, VLM, MoE, MLM, LCM, LAM, SAM · Next: RAG Explained for Beginners: How AI Answers Questions From Your Own Documents