# pgvector in Practice: Embeddings and Vector Search in Postgres

> Everything you need to run vector search inside Postgres: the vector type, distance operators, HNSW vs IVFFlat indexes, query-time recall tuning and filtered search with iterative scans.

- Published: 2026-09-26
- Updated: 2026-10-07
- Category: Frameworks & SDKs
- Type: guide
- Tags: embeddings, pgvector, postgres, rag
- Sources: 2
- Canonical: https://rajatxautomatedcontent.vercel.app/articles/pgvector-embeddings-postgres-guide

---

## Overview

pgvector adds vector similarity search to Postgres, so embeddings can live next to the rows they describe and be queried with ordinary SQL, joins and transactions [S1]. For many retrieval-augmented generation (RAG) and recommendation workloads, that removes an entire system from the architecture. Managed Postgres providers such as Neon offer it as an extension you can enable per database [S2].

## Key concepts

### Enable the extension and store vectors

```sql
CREATE EXTENSION vector;

CREATE TABLE documents (
  id bigserial PRIMARY KEY,
  content text NOT NULL,
  embedding vector(1536)
);
```

The dimension in `vector(1536)` must match the output size of the embedding model you use.

### Distance operators

pgvector provides these distance operators [S1]:

- `<->` — L2 (Euclidean) distance
- `<#>` — negative inner product
- `<=>` — cosine distance
- `<+>` — L1 distance
- `<~>` and `<%>` — Hamming and Jaccard distance for binary vectors

`<#>` returns the _negative_ inner product because Postgres only supports ascending-order index scans on operators [S1]. For cosine similarity, subtract the distance from one:

```sql
SELECT id, content, 1 - (embedding <=> $1) AS cosine_similarity
FROM documents
ORDER BY embedding <=> $1
LIMIT 5;
```

## Practical walkthrough: indexing

By default pgvector performs exact nearest-neighbor search, which gives perfect recall [S1]. That is often fine for small tables. As data grows, add an approximate index. There are two types [S1].

**HNSW** builds a multilayer graph. It has better query performance than IVFFlat in terms of the speed–recall trade-off, but slower build times and higher memory use. Because there is no training step, you can create it before the table has any data [S1].

```sql
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
```

**IVFFlat** divides vectors into lists and searches only a subset of them. It builds faster and uses less memory than HNSW, but has lower query performance [S1]. Create it after the table has some data, and choose the number of lists with care — the README suggests starting at rows / 1000 for up to one million rows [S1].

```sql
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
```

Match the operator class to the operator in your query — `vector_cosine_ops` for `<=>`, `vector_l2_ops` for `<->` and `vector_ip_ops` for `<#>` [S1] — otherwise the planner cannot use the index.

### Tune recall at query time

```sql
SET hnsw.ef_search = 100; -- 40 by default; higher improves recall, lowers speed
SET ivfflat.probes = 10;  -- 1 by default; more probes improve recall
```

Both defaults come from the pgvector README [S1].

## Best practices

- **Filter with iterative scans.** With approximate indexes, filtering is applied after the index is scanned, so a selective `WHERE` clause can return fewer rows than your `LIMIT` [S1]. Starting with version 0.8.0, iterative index scans keep scanning more of the index until enough results are found [S1]:

```sql
SET hnsw.iterative_scan = strict_order;
```

- **Know the dimension limits.** Indexed `vector` columns support up to 2,000 dimensions; the half-precision `halfvec` type supports up to 4,000 and halves storage [S1].
- **Keep vectors next to the data.** Store embeddings in the same table, or a one-to-one side table, so updates and deletes stay transactional.
- **Measure recall.** Compare approximate results with exact search on a sample of real queries before and after tuning.

## Pitfalls

- Ordering by `<=>` while the index uses `vector_l2_ops` — the index is silently skipped.
- Building an IVFFlat index on an empty table — its lists are poorly clustered; build after loading data [S1].
- Forgetting that `<#>` is a _negative_ inner product — results sort in the opposite order to what you expect.

Related reading: before you embed content fetched from the web, make sure the fetcher cannot be abused — see [SSRF-Safe Fetching in Node.js](/articles/ssrf-safe-fetch-nodejs).

## FAQ

**Should I use HNSW or IVFFlat?**

Default to HNSW for its better speed-recall trade-off. Choose IVFFlat when index build time or memory is the tighter constraint.

**Do I need a vector index at all?**

Not for small tables. Without an index pgvector runs exact nearest-neighbor search with perfect recall; add an approximate index when query latency starts to matter.

**How many dimensions can pgvector index?**

Indexed vector columns support up to 2,000 dimensions; the half-precision halfvec type supports up to 4,000.

## Sources

- [S1] pgvector: Open-source vector similarity search for Postgres — pgvector. <https://github.com/pgvector/pgvector> (retrieved 2026-09-30, trust: official)
- [S2] The pgvector extension — Neon. <https://neon.com/docs/extensions/pgvector> (retrieved 2026-09-30, trust: high)

---

Source: AI Dev Hub — https://rajatxautomatedcontent.vercel.app/articles/pgvector-embeddings-postgres-guide
