Search "cheap flights to Goa" in a keyword index and a page titled "Budget airfare to Goa, India" may not appear, because the words barely overlap. A person sees they mean the same thing. Vector databases are how software learns to see it too.
This guide explains what vector databases are, how similarity search works under the hood, which index types you will meet (HNSW and IVF), and how to run vector search yourself with Postgres and Node.js. It is written for developers who have heard "embeddings" and "vector store" and want a clear mental model before choosing a tool.
Direct answer: what is a vector database?
- A vector database stores high-dimensional vectors (embeddings) along with metadata, and returns the vectors nearest to a query vector.
- An embedding model turns text, images or other data into vectors so that similar meanings are close together.
- To stay fast at scale, most systems use approximate nearest neighbour (ANN) indexes such as HNSW or IVF, trading a little recall for large speed gains.
- Vector search powers semantic search, recommendations and the retrieval step of RAG. It complements keyword search; it does not replace it.
Table of contents
- Embeddings: meaning as numbers
- How similarity search works
- Why ANN indexes exist: HNSW and IVF
- Hands-on: vector search with Postgres and Node.js
- Choosing a vector database
- Vector search in real applications
- Common mistakes
- Best practices
- Frequently asked questions
- Conclusion
- References
Embeddings: meaning as numbers
An embedding is a list of floating-point numbers produced by a model. The model is trained so that texts with similar meaning produce vectors that are close in space. OpenAI's embeddings guide documents text-embedding-3-small (1536 dimensions by default) and text-embedding-3-large (3072 by default), and says the dimensions parameter is the suggested way to get shorter vectors.
Two rules follow from this:
- Compare vectors only from the same model. A vector is meaningful relative to the model that produced it.
- Dimensions cost money. Storage and search time grow with vector length, so use the smallest size that gives acceptable retrieval quality on your data.
How similarity search works
Given a query vector, "closest" needs a distance function. The common ones:
| Metric | What it measures | pgvector operator | Typical use |
|---|---|---|---|
| Cosine distance | Angle between vectors, ignoring length | <=> | Text embeddings (most common) |
| Inner product | Dot product (negated in pgvector) | <#> | Normalised vectors, recommendation |
| Euclidean (L2) | Straight-line distance | <-> | Image and general numeric features |
Check which metric your embedding model recommends. Many text embedding models return vectors normalised to unit length, in which case cosine similarity and inner product give the same ranking.
Exact search compares the query against every stored vector. It is perfectly accurate and fine for thousands to low hundreds of thousands of vectors. Beyond that, scanning everything becomes too slow, which is why indexes exist.
Why ANN indexes exist: HNSW and IVF
Approximate nearest neighbour indexes avoid comparing against everything. They return very likely nearest neighbours quickly. The fraction of true neighbours they find is called recall.
HNSW (Hierarchical Navigable Small World) builds a layered graph. The search enters at the top layer with few nodes, greedily walks towards the query, and drops to denser layers to refine. Build parameters (such as m and ef_construction) and a query parameter (ef_search) trade speed, memory and recall. HNSW usually gives strong recall and query speed but uses more memory and builds more slowly.
IVF (Inverted File) clusters vectors into lists around centroids. A query checks only the nearest few lists. It builds faster and uses less memory, but you must build it after loading representative data, because the centroids are computed from existing rows, and you tune how many lists to probe.
flowchart TD
Q[Query vector] --> I{Index type}
I -->|HNSW| H[Enter top graph layer]
H --> H2[Walk to closer neighbours layer by layer]
H2 --> R[Candidate nearest vectors]
I -->|IVF| V[Find nearest centroids]
V --> V2[Scan only those lists]
V2 --> R
R --> S[Rank by distance, return top-k]The key engineering point: ANN is a recall versus latency versus memory trade-off. There is no universally best setting. Measure recall against exact search on a sample of your own queries, then tune.
Hands-on: vector search with Postgres and Node.js
If you already run PostgreSQL, the pgvector extension adds a vector type, distance operators and HNSW/IVFFlat indexes. This keeps embeddings next to your normal data, so permissions, transactions and joins work as usual.
-- schema.sql
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE articles (
id bigserial PRIMARY KEY,
tenant_id integer NOT NULL,
title text NOT NULL,
body text NOT NULL,
embedding vector(1536) NOT NULL -- must match the embedding model's dimensions
);
-- Approximate index for cosine distance (operator class must match the query operator)
CREATE INDEX articles_embedding_hnsw
ON articles USING hnsw (embedding vector_cosine_ops);
CREATE INDEX articles_tenant_idx ON articles (tenant_id);
Two documented details are easy to miss: the operator class (vector_cosine_ops) must match the operator used in ORDER BY (<=>), otherwise the index is not used; and the index type cannot be switched in place later, so test before you load production data.
Now the Node.js side, using pg and the OpenAI SDK:
npm install pg openai
// search.mjs: insert and query with pgvector (example, add validation and pooling config for production)
import pg from "pg";
import OpenAI from "openai";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const openai = new OpenAI();
const EMBED_MODEL = "text-embedding-3-small"; // 1536 dimensions by default
async function embed(text) {
const res = await openai.embeddings.create({ model: EMBED_MODEL, input: text });
return JSON.stringify(res.data[0].embedding); // pgvector accepts '[0.1,0.2,...]'
}
export async function addArticle(tenantId, title, body) {
const vector = await embed(`${title}\n\n${body}`);
await pool.query(
"INSERT INTO articles (tenant_id, title, body, embedding) VALUES ($1, $2, $3, $4::vector)",
[tenantId, title, body, vector],
);
}
export async function search(tenantId, query, limit = 5) {
const vector = await embed(query);
const { rows } = await pool.query(
`SELECT id, title, 1 - (embedding <=> $2::vector) AS similarity
FROM articles
WHERE tenant_id = $1
ORDER BY embedding <=> $2::vector
LIMIT $3`,
[tenantId, vector, limit],
);
return rows;
}
await addArticle(1, "Budget airfare to Goa, India", "Tips for finding low-cost flights to Goa during the monsoon.");
console.log(await search(1, "cheap flights to Goa"));
await pool.end();
Example output (similarity values will differ):
[ { id: '1', title: 'Budget airfare to Goa, India', similarity: 0.71 } ]
Note 1 - (embedding <=> $2): pgvector's <=> returns distance, so 1 - distance gives a cosine similarity for display. Ordering by the raw distance expression is what lets the index be used.
To tune recall at query time, pgvector exposes hnsw.ef_search (default 40 in the documentation I checked):
SET hnsw.ef_search = 100; -- higher = better recall, slower queries
Filtering deserves care. With an approximate index, a restrictive WHERE clause can leave fewer rows than LIMIT, because the index returns a candidate set that is then filtered. Newer pgvector versions add iterative index scans to address this; check the pgvector README for your installed version, and verify with EXPLAIN ANALYZE. Our chapter on PostgreSQL indexes and EXPLAIN ANALYZE shows how.
Also check dimension limits. At the time of writing, the pgvector README documents limits on how many dimensions can be indexed for the vector type (and a higher limit for halfvec). If you use a 3072-dimension model, check those limits or request shorter vectors through the dimensions parameter.
Choosing a vector database
| Option | Strengths | Trade-offs | Good fit |
|---|---|---|---|
| In-memory array | Zero setup, easy to reason about | Lost on restart, no scaling | Prototypes, tests, tiny corpora |
| Postgres + pgvector | One system, transactions, SQL filters, familiar ops | Scaling and tuning are on you; very large indexes need care | Most apps already on Postgres, up to millions of vectors |
| Dedicated vector database (managed or self-hosted) | Built for scale, advanced filtering, managed operations | Another service, data sync, vendor-specific APIs and cost | Very large or high-throughput workloads |
| Search engine with vector support | Hybrid keyword plus vector in one query | Operational weight of a search cluster | Products where keyword relevance matters as much as semantics |
I deliberately give no throughput numbers here. Benchmarks depend on dimensions, recall target, filters and hardware, so run one on your data before deciding. A useful default: start with what you already operate, and move only when you can name the limit you hit.
Vector search in real applications
A hypothetical example: a B2B SaaS product with per-customer knowledge bases. Each chunk row carries tenant_id, source_url, updated_at and the embedding.
- Isolation. Always filter by tenant in SQL. Do not retrieve globally and filter in application code.
- Freshness. When a document changes, delete its old chunks and insert new ones in one transaction; stale vectors silently produce stale answers.
- Model changes. Store the embedding model name next to each vector. Changing models means re-embedding everything into a new column or table, then switching over.
- Hybrid search. Keep a keyword path (Postgres full-text search, see full-text search chapter) for exact terms such as SKUs and error codes, and merge the two result lists. The next article, How to Build an AI-Powered Search System, does exactly that.
- Operations. Index builds take time and memory; plan them like any large migration.
Common mistakes
- Mixing embedding models between documents and queries, which makes distances meaningless.
- Mismatched operator and index. Querying with
<->against a cosine-ops index silently falls back to a sequential scan. - Dimension mismatch. The column is
vector(1536)but the model returned 3072 values, so inserts fail. - Building an IVF index on an empty table. Centroids come from existing data; load data first.
- Assuming ANN is exact. Measure recall against exact search and tune parameters.
- Filtering after retrieval in application code. This leaks data across tenants and returns too few results.
- Embedding huge documents as one vector. One vector for a 40-page file blurs everything; chunk it.
- Not storing metadata. Without source and version fields you cannot cite, filter or re-index.
- Replacing keyword search entirely. Pure vector search is weak on rare exact tokens.
Best practices
- Normalise how you prepare text (strip boilerplate, keep titles with their content) before embedding.
- Use the smallest embedding dimension that meets your quality target.
- Keep metadata and embeddings in the same row or transaction.
- Evaluate with a labelled set of queries and track recall and relevance, not just latency.
- Use hybrid retrieval where exact matches matter.
- Run
EXPLAIN ANALYZEto confirm the vector index is actually being used.
Conclusion
A vector database is a nearest-neighbour search engine for embeddings. The concepts that matter are few: embeddings encode meaning, distance functions define "similar", and ANN indexes such as HNSW and IVF trade a little recall for a lot of speed. Everything else (metadata, tenancy, freshness, hybrid search) is ordinary database engineering.
If you run Postgres, try pgvector on a table of your own documents and check results with EXPLAIN ANALYZE. Then continue with How to Build an AI-Powered Search System or read how RAG architecture puts vector search to work.
References
- pgvector on GitHub (README: operators, HNSW, IVFFlat, limits)
- OpenAI: Embeddings guide
- Efficient and robust approximate nearest neighbor search using HNSW graphs (Malkov & Yashunin)
- PostgreSQL documentation: Indexes
- node-postgres documentation
Written by Shivam Thakur, a Software Engineer focused on web applications, SaaS platforms and modern software products. More at shivamthakur.me.

