---
title: "What are embeddings, and how do I compare them?"
description: "An embedding is a list of numbers that places a piece of text in a space where similar meanings sit close together. You compare two of them with cosine similarity."
url: https://www.danny.engineering/answer/ai/what-are-embeddings-and-how-do-i-compare-them
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:35:00.000Z
tags: ["AI"]
---

# What are embeddings, and how do I compare them?

## The short answer


An embedding is a fixed-length vector of floating-point numbers, typically 512 to 3,072 of them, produced by a model from a piece of text. The model is trained so that texts with similar meaning produce vectors pointing in similar directions. You compare two embeddings with cosine similarity: 1 means the same direction, 0 means unrelated, and negative values mean opposed. Embed your query with the same model you used for your documents, then rank documents by similarity to the query.


```typescript
function cosineSimilarity(a: number[], b: number[]): number {
  let dot = 0;
  let normA = 0;
  let normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
```


## What it means


Think of each dimension as one of many learned features of meaning. No single number is interpretable on its own, but together they place the text somewhere in a high-dimensional space. "Reset my password" and "I cannot log in" land near each other because they are about the same thing, even though they share no words. "Bank" near "river" and "bank" near "mortgage" land in different places because the model reads the surrounding text.


Two things follow from this. First, embeddings are only comparable within one model. A vector from `voyage-3` and a vector from `text-embedding-3-small` may both have 1,024 numbers, but they live in different spaces, and comparing them produces a confident-looking, meaningless score. Second, direction matters more than length. Cosine similarity measures the angle between two vectors and ignores their magnitude, which is why it is the standard comparison for text.


Anthropic does not offer an embeddings endpoint. Voyage AI's `voyage-3` family is recommended by Anthropic; OpenAI's `text-embedding-3-small` is another common choice. Whichever you pick, wrap it in one function so the model name lives in exactly one place.


## How to do it


### Embed query and documents with the same model


```typescript
const EMBEDDING_MODEL = 'voyage-3'; // or 'text-embedding-3-small'

async function embed(texts: string[]): Promise<number[][]> {
  // Call your provider's embeddings endpoint with EMBEDDING_MODEL.
  // It returns one vector per input text, in the same order.
  const vectors: number[][] = await callProvider(EMBEDDING_MODEL, texts);
  return vectors;
}
```


Batch your documents (most providers accept dozens of texts per call) and embed the query on its own at request time. Some providers let you mark an input as a query or a document and tune the vector accordingly; check your provider's docs.


### Rank by cosine similarity


```typescript
const [queryVector] = await embed([question]);

const ranked = documents
  .map((doc) => ({ doc, score: cosineSimilarity(queryVector, doc.embedding) }))
  .sort((a, b) => b.score - a.score)
  .slice(0, 5);
```


This in-memory version is fine for a few thousand documents. Beyond that, move the comparison into the database (pgvector's `<=>` operator is cosine distance, which is 1 minus cosine similarity) and add an index.


### Normalise once, then use the dot product


Cosine similarity is the dot product divided by the product of the two lengths. If every vector has length 1, the denominator is 1 and the dot product _is_ the cosine similarity. Normalise each vector when you store it and the query when it arrives, and you skip two square roots and a division per comparison. Many embedding models already return unit-length vectors; check the docs, or check `Math.sqrt(dot(v, v))` on one and see whether it is 1.


```typescript
function normalise(v: number[]): number[] {
  const length = Math.sqrt(v.reduce((sum, x) => sum + x * x, 0));
  return v.map((x) => x / length);
}

function dot(a: number[], b: number[]): number {
  return a.reduce((sum, x, i) => sum + x * b[i], 0);
}
```


In pgvector, normalised vectors let you use the inner product operator `<#>`, which is cheaper than `<=>` and gives the same ranking.


### Use full-text search for exact matching


Embeddings are fuzzy by design. They are poor at matching an error code, a SKU, a function name or an exact phrase, because a one-character difference barely moves the vector. For those, Postgres full-text search or a plain `ILIKE` is both faster and more accurate.


```sql
SELECT id, content
FROM chunks
WHERE to_tsvector('english', content) @@ websearch_to_tsquery('english', $1)
LIMIT 20;
```


A common pattern is hybrid search: run both the vector query and the full-text query, merge the two result lists, and let the top of each through. You get semantic matches for vague questions and exact matches for identifiers.


### Mind dimensions and storage


A 1,024-dimension vector of 32-bit floats is 4 KB. One million chunks is 4 GB before the index. More dimensions give slightly better retrieval and cost proportionally more to store and compare. Some models let you request fewer dimensions; check your provider's docs. pgvector also offers a `halfvec` type that stores 16-bit floats and halves the footprint with little loss. Pick a dimension count when you create the table, because the column type `vector(1024)` is fixed.


### Record the model with the data


Store the embedding model's name and version alongside the vectors, either as a column or as a property of the table. When you change models, re-embed everything in one migration. A table containing vectors from two models will keep returning results, and they will be wrong in a way that is hard to spot.


```sql
ALTER TABLE chunks ADD COLUMN embedding_model text NOT NULL DEFAULT 'voyage-3';
```


## Common pitfalls

- **Mixing models.** The single most common embeddings bug. Query and documents must come from the same model, and so must every row in the table.
- **Expecting exact matches.** If users search for identifiers, codes or quoted phrases, add full-text search. Embeddings will return something plausible and often wrong.
- **Treating scores as absolute.** A similarity of 0.8 means different things in different models. Set any threshold empirically by looking at real queries, and expect to revisit it when you change models.
- **Embedding text that is too long.** Each model has an input limit, and some truncate silently. Chunk documents before embedding them so the vector represents the whole passage.
- **Embedding different text than you compare.** If you prepend a title to each chunk before embedding (a good idea), the stored vector reflects the title plus text. Keep the stored text and the embedded text identical so you can re-embed later.
- **Comparing in JavaScript at scale.** Pulling every vector into Node to compute cosine similarity works for thousands of rows and falls over at hundreds of thousands. Let the database do it with an index.

## Related reading

- [Embeddings](https://platform.claude.com/docs/en/build-with-claude/embeddings)
- [pgvector](https://github.com/pgvector/pgvector)
- [Postgres full-text search](https://www.postgresql.org/docs/current/textsearch.html)
