Embedding & Vector Search — AI Web

An embedding turns text into a vector: a list of numbers that stands for the text's meaning. Texts with similar meanings have vectors that point the same way…

The Bookshop shelves are arranged by theme: novels about school in one corner, history novels in another. A customer looking for "a novel about a school" walks to the right corner and takes the nearest book. An embedding gives every text one point on a map, like the place of each book on the shelf plan, except the map has 1,536 directions instead of two. The point is a list of numbers, called a vector, that stands for the text's meaning. Texts with similar meanings get similar numbers, so their points are close together, like books on one theme in one corner. Vector search means finding the book points closest to the question's point.

Embedding: text becomes a list of numbers

The Bookshop assistant should be able to answer "is there a novel about a school on Belitung?". The Rainbow Troops synopsis (the short summary of the story) says "on Belitung attend a Muhammadiyah primary school". The words "school on Belitung" never appear in that order, so the SQL query WHERE synopsis LIKE '%school on Belitung%' finds nothing. An embedding searches by meaning, not by identical letters.

An embedding model is also called over HTTP. This Bookshop server code uses the OpenAI SDK to embed (turn into vectors) the four synopses. books is an array of those four books, each with a synopsis field:

import OpenAI from "openai";
const client = new OpenAI();

const res = await client.embeddings.create({
  model: "text-embedding-3-small",
  input: books.map((b) => b.synopsis), // 4 synopses in 1 request
});
const vectors = res.data.map((d) => d.embedding);
console.log(vectors.length, vectors[0].length); // 4 1536

A toy embedding you can calculate by hand

We can't compute a model's numbers on paper. So this lesson and the Lab use a toy embedding: word counting (bag-of-words). Each word is one dimension (one direction on the map above), and its value is how many times the word appears. Common words a, an, the, of, in, on, at, to, and, from, by, is, that, about, their, her, his, it are dropped first, because they are in almost every sentence. Word counting is not an embedding model: it only catches identical words. But its similarity formula is exactly the one used for a model's vectors. Here are the word counts:

Text Words counted Vector length
"a novel about a school on Belitung" novel, school, belitung (once each) √3 = 1.732
The Rainbow Troops synopsis 15 words, once each, including school and belitung √15 = 3.873
This Earth of Mankind synopsis 20 words, including school √20 = 4.472
Beauty Is a Wound synopsis 16 words √16 = 4.000
The Dancer synopsis 15 words √15 = 3.873

The length of a vector comes from the Pythagorean formula: the square root of the sum of all its numbers squared. The question's vector holds three ones, so its length is √(1² + 1² + 1²) = √3.

Cosine similarity by hand

Cosine similarity measures how much two vectors point the same way. Picture each vector as an arrow from the zero point of the map to its point: cosine looks at the direction of the arrows, not their length. The formula:

cosine(a, b) = (a · b) / (|a| × |b|)

a · b is the dot product: multiply the numbers in the same dimension, then add them up. |a| is the length of vector a. The result is 1 when they point exactly the same way, 0 when they have nothing in common, and can go down to -1 when they point opposite ways. Word counts are never negative, but the numbers in a model's vectors can be.

The question and The Rainbow Troops synopsis share two words, "school" and "belitung". In every other dimension, one of the two vectors has a 0, so their dot product is only 1 × 1 + 1 × 1 = 2. Here are all four books:

Book Shared words Dot product Cosine
The Rainbow Troops school, belitung 2 2 / (1.732 × 3.873) = 2 / 6.708 = 0.298
This Earth of Mankind school 1 1 / (1.732 × 4.472) = 1 / 7.746 = 0.129
Beauty Is a Wound (none) 0 0
The Dancer (none) 0 0

The Rainbow Troops comes first. The cosine function below does the same calculation for two arrays that hold the same count of numbers. findSimilar uses it to rank the books:

function cosine(a, b) {
  let dot = 0, lengthA = 0, lengthB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i]; // dot product
    lengthA += a[i] * a[i]; // sum of squares
    lengthB += b[i] * b[i];
  }
  return dot / (Math.sqrt(lengthA) * Math.sqrt(lengthB));
}

function findSimilar(questionVector, books, k = 2) {
  return books
    .map((b) => ({ title: b.title, score: cosine(questionVector, b.vector) }))
    .sort((x, y) => y.score - x.score) // biggest score first
    .slice(0, k); // take the top k (top-k)
}

Normalisation: cosine becomes the dot product

Normalising means dividing every number by the vector's length, so the length becomes exactly 1. The direction doesn't change. The question's vector becomes three numbers 1 / 1.732 = 0.577, and The Rainbow Troops vector becomes fifteen numbers 1 / 3.873 = 0.258. They share two dimensions, school and belitung, so their dot product is 2 × 0.577 × 0.258 = 0.298. That is the same as the cosine above, because both lengths are now 1, so the divisor is 1 × 1.

OpenAI's "Vector embeddings" guide (checked October 2026) says OpenAI embeddings are already normalised to length 1. So the dot product is enough. The same guide says cosine similarity and Euclidean distance (the straight-line distance between two points) give identical rankings for vectors of length 1.

One note from that guide: if you shorten a vector yourself (say with slice(0, 256)) instead of using dimensions, normalise it again before using the dot product.

Index time and query time

This search happens at two moments:

  1. Index time, once per book: embed the synopsis, then store its vector with the book id. This collection of vectors, ready to search, is called the index. When a synopsis changes or a new book arrives, embed that book again.
  2. Query time, for every question: embed the question with the same model, compute its similarity to every book vector, sort, then take the top k.

For 4 books, the vectors can live in a JSON column or in memory. With thousands of books, comparing them one by one gets slow. That is what a vector database (a database made to store and search vectors) is for. It has its own lesson later.

💡 Why cosine, not plain distance

Euclidean distance on vectors that aren't normalised is affected by the length of the text. For a distance, a smaller number means more similar. In the Lab (which shows the books' Indonesian titles), try "a novel about a school on Belitung" with Euclidean and no normalisation. The Dancer (0 shared words, distance 4.243) ranks above This Earth of Mankind (1 shared word, distance 4.583), because The Dancer's synopsis is shorter. Cosine only looks at direction, so This Earth of Mankind (0.129) stays above The Dancer (0). Once normalised, all three measures (cosine, dot product and Euclidean distance) give the same order.

Other metrics (measures of distance or similarity) have other jobs:

For meaning, the usual metric is cosine similarity.

⚠️ Why are the search results off?

TL;DR: An embedding turns text into a vector: a list of numbers that stands for the text's meaning. Texts with similar meanings have vectors that point the same way. The model text-embedding-3-small gives 1,536 numbers (shorter with the dimensions field) and costs $0.02 per 1 million tokens as of October 2026. Similarity is measured with cosine similarity: the dot product divided by the product of both vectors' lengths (the square root of the sum of squares). The dot product multiplies the numbers in the same position, then adds them up. The result is 1 for the same direction and 0 for unrelated texts. An example with word counting (a toy embedding): "a novel about a school on Belitung" and The Rainbow Troops synopsis = 2 / (1.732 × 3.873) = 0.298. OpenAI's vectors are already normalised to length 1, so the dot product is enough. Embed (turn into a vector) every book once (index time). Embed each question with the same model (query time), sort from the most similar, then take the top k (the k best results).

⚡ Text becomes a list of numbers

Write:

const res = await client.embeddings.create({
  model: "text-embedding-3-small",
  input: books.map((b) => b.synopsis), // 4 synopses in 1 request
});
const vectors = res.data.map((d) => d.embedding);
console.log(vectors.length, vectors[0].length); // 4 1536

Meaning: client is an object from the OpenAI SDK, and books holds the Bookshop's four books. client.embeddings.create sends the four synopses (short story summaries) to the embedding model text-embedding-3-small in one request. An embedding turns each text into a vector, a list of numbers that stands for its meaning: here 4 vectors of 1,536 numbers each. A single number inside means nothing on its own. Only the comparison with other vectors is useful.

⚡ Cosine: how much they point the same way

Write:

cosine(a, b) = (a · b) / (|a| × |b|)
Guess first: every number in vector B is twice the number in vector A. They point exactly the same way; B is only twice as long. What is their cosine?

Still 1. Cosine only looks at direction, not length, because the dot product is divided by the product of both lengths.

Meaning: Cosine similarity measures how much two vectors point the same way. a · b is the dot product: multiply the numbers in the same position, then add them up. |a| and |b| are the two vectors' lengths (the square root of the sum of squares). 1 means the same direction, 0 means nothing in common, -1 means opposite. Texts with similar meanings have vectors pointing the same way.

⚡ Length 1, the dot product is enough

Meaning: Normalising divides every number in a vector by its length, so the length becomes 1. OpenAI's vectors are already normalised, so their dot product equals the cosine: the divisor in the cosine formula becomes 1 × 1. If you shorten a vector yourself with slice, its length is no longer 1, so normalise it again first.

⚡ Index time and query time

Meaning: At index time, once per book, turn each synopsis into a vector (embed it) and store the vector. At query time, for every question, embed the question with the same model and compare it with every book vector. Sort from the most similar, then take the top k (the k best books).

What you will learn