RAG

What are embeddings? Vector search explained in TypeScript

Keyword search has a classic failure: a user asks "Can I get my train ticket paid back?" and your handbook says "submit receipts within 30 days to get reimbursed." Not one word in common. includes() finds nothing, and the user decides your docs are useless.

Embeddings fix that by comparing meaning instead of spelling. They are the engine under semantic search, RAG, recommendations, deduplication and agent memory. This post explains what they are, shows them working (and failing) on real output, and gives you about 40 lines of TypeScript that run on your laptop without an API key.

What is an embedding?#

An embedding model takes a piece of text and returns a fixed-length list of numbers, a vector. The model used here, all-MiniLM-L6-v2, returns 384 numbers for any sentence you give it.

The numbers on their own mean nothing to you. What matters is the geometry: the model was trained so that texts with similar meaning get vectors pointing in similar directions. Think of every sentence as a point on a map with 384 dimensions instead of two, where "refund my ticket" and "get reimbursed" end up in the same neighborhood.

If you want a software analogy: it is a hash function with the opposite goal of a cryptographic hash. A good password hash makes similar inputs produce wildly different outputs. An embedding makes similar inputs produce similar outputs, on purpose.

Embed yourdocs oncetext -> 384numbers eachEmbed thequestionsame model!Compare bycosinerank closestfirstTop resultsshow them, orfeed RAG
Indexing happens once. Each search is one embedding call plus some multiplication.

How do you compare two vectors?#

With cosine similarity: how much two vectors point in the same direction, from -1 to 1. For text embeddings, higher means closer in meaning. It is a loop with three running sums:

ts
/** -1 to 1. Closer to 1 = closer in meaning. */
export function cosine(a: number[], b: number[]): number {
  let dot = 0;
  let na = 0;
  let nb = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    na += a[i] * a[i];
    nb += b[i] * b[i];
  }
  return dot / Math.sqrt(na * nb);
}

If the vectors are normalized to length 1 (the code below asks the model for that), the bottom of the fraction is 1 and cosine similarity is just the dot product. Many vector databases use that shortcut.

Search a handbook by meaning#

The full search, using transformers.js to run the model locally. The first run downloads the model files from Hugging Face and caches them.

bash
npm install @huggingface/transformers
ts
import { pipeline } from "@huggingface/transformers";

const MODEL = "Xenova/all-MiniLM-L6-v2"; // 384 numbers per text
const extract = await pipeline("feature-extraction", MODEL);

/** Text in, vectors out. One vector per text. */
export async function embed(texts: string[]): Promise<number[][]> {
  const opts = { pooling: "mean", normalize: true } as const;
  const out = await extract(texts, opts);
  return out.tolist() as number[][];
}

pooling: "mean" averages the per-token vectors into one vector for the whole text, and normalize scales it to length 1. Then indexing and search:

ts
export interface Doc {
  text: string;
  vector: number[];
}

/** Embed your documents once, up front. */
export async function index(texts: string[]): Promise<Doc[]> {
  const vectors = await embed(texts);
  return texts.map((text, i) => ({ text, vector: vectors[i] }));
}

/** Embed the question, rank the documents by meaning. */
export async function search(query: string, docs: Doc[], k = 3) {
  const [q] = await embed([query]);
  return docs
    .map((d) => ({ text: d.text, score: cosine(q, d.vector) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

Six handbook lines (deploys, on-call, expenses, code review, incidents, holidays) and three questions that share no keyword with their answer. Real scores:

QuestionBest matchScoreRunner-up
Can I get my train ticket paid back?Expenses0.33Holidays, 0.08
Who has to approve my changes?Code review0.39On-call, 0.17
When does the pager duty switch?On-call0.35Holidays, 0.27

All three right, with zero shared words. That is the magic trick. Now the part most tutorials skip.

Where embeddings fail#

Shared words still pull the score. Compare "How do I deploy to production?" with two sentences:

SentenceScore
"Shipping a release to prod" (same meaning, different words)0.47
"How do I deploy a cat?" (different meaning, same words)0.54

The nonsense question scores higher than the real paraphrase. Embeddings capture meaning and wording, and a small model leans on wording more than you would like.

Small models miss. "How do I get my code live?" should find the deploy line. This model ranks code review first (0.31). Plausible-ish, wrong.

Scores are relative, not absolute. 0.33 was a confident match above, with the runner-up at 0.08. There is no universal "0.5 means relevant": thresholds depend on the model and your data. Look at the gap between the first and second result, and measure on real questions.

What to do about it:

  • Try a stronger model for production. This one is built for speed and size. Larger embedding models, including hosted ones, are usually better at this, but do not take that on faith: run your own questions through each candidate.
  • Combine with keyword search (hybrid search). Keywords catch exact names, error codes and IDs that embeddings blur; embeddings catch paraphrases.
  • Test retrieval like any other code. Collect 20 real questions with the right answer and track how often it ranks first. That is an eval, and it will tell you more than any benchmark.

Rules that save you a rewrite#

  1. Same model for documents and questions. Vectors from different models live in different spaces and cannot be compared. Store the model name next to every vector.
  2. Chunk long text. all-MiniLM-L6-v2 truncates input longer than 256 word pieces, silently. Split documents into passages (for example by heading), and embed each one.
  3. Embed once, store, reuse. Indexing is the slow part. Searching is one embedding call plus multiplication.
  4. Keep the original text. You search with vectors, but you show (or send to the model) the text.

Do you need a vector database?#

Not on day one. Comparing a query against 10,000 vectors of 384 numbers took about 20 to 25 milliseconds per query in plain JavaScript on my machine, with a loop no smarter than the one above. A few thousand documents in memory, or a JSON file, is fine.

You need a real index (a vector database, or an extension such as pgvector in Postgres) when you have hundreds of thousands of vectors or more, need metadata filters ("only docs this user can see"), or update vectors constantly. In my opinion, start with an array, measure, and move when the numbers tell you to.

How I tested this#

The code ran under Node 24 with @huggingface/transformers 4.3.1 and the all-MiniLM-L6-v2 model. The tests assert that vectors have 384 numbers, that the three keyword-free questions rank the right line first (and genuinely share no keyword with it), that the "deploy a cat" sentence really does outscore the paraphrase, that "get my code live" really does miss, and that brute force over 10,000 vectors stays well under 200 ms. Every score in this post is copied from those test runs.

Next on the roadmap: RAG for beginners, which is this search plus "now answer using these passages".

Sources: all-MiniLM-L6-v2 model card, transformers.js.

Frequently asked questions

What are embeddings in an LLM?

An embedding is a list of numbers that represents a piece of text. Embedding models are trained so that texts with similar meaning get similar vectors, which lets you compare meaning with simple math. LLMs also have an internal embedding layer for tokens, but for search you use a dedicated embedding model that produces one vector per sentence or passage.

What is cosine similarity?

It measures how much two vectors point in the same direction, from -1 to 1. For text embeddings, a higher score means closer meaning. If the vectors are normalized to length 1, cosine similarity is just the dot product.

Do I need a vector database?

Not at first. Comparing a query against 10,000 vectors of 384 numbers took about 20 to 25 milliseconds in plain JavaScript on my machine. Reach for a vector database or an index such as pgvector when you have hundreds of thousands of vectors, need filtering, or need to update them often.

Can I mix embeddings from different models?

No. Each model has its own vector space, so vectors from two models cannot be compared. Store the model name next to your vectors and re-embed everything if you switch.

What is the difference between embeddings and RAG?

Embeddings are the search step. RAG (retrieval-augmented generation) uses that search to find relevant passages and puts them in the prompt so the model answers from your documents.