If you’ve ever typed “the movie where the toys are alive when nobody is watching” into a search bar and got Toy Story back, you’ve used semantic search. None of those words has to appear in the movie’s plot, so keyword search can miss it. Semantic search compares meaning instead. A model turns each text into an embedding, a list of numbers, and texts with similar meanings get similar embeddings.

In PostgreSQL, you get this with pgvector, an open-source PostgreSQL extension for vector search. You store an embedding for each row in a vector column, then sort by distance with ORDER BY embedding <=> query LIMIT 10.

In this guide, we’ll load about 34,000 movie plots from Wikipedia, search them with SQL, compare HNSW and IVFFlat indexes, fix a common filtering problem, and see how purpose-built search engines handle the same workload.

Note: We ran every example on PostgreSQL 19.0, pgvector 0.8.7, Python 3.15, sentence-transformers 6.3.0, and Typesense 30.2, in Docker on an Apple M5 Pro. Query timings are EXPLAIN ANALYZE execution times, the median of 5 runs after a warm-up run. Your numbers will differ.

Setting Up pgvector in Docker

The quickest way to get going is the official pgvector Docker image, which ships Postgres with the extension built in:

docker run -d \
  --name postgres-vector \
  --shm-size=1g \
  -e POSTGRES_PASSWORD=postgres \
  -p 127.0.0.1:5432:5432 \
  pgvector/pgvector:0.8.7-pg19

--shm-size=1g raises Docker’s default 64 MB of shared memory, which a parallel HNSW index build runs out of (No space left on device) once you raise maintenance_work_mem later on.

Open psql inside the container:

docker exec -it postgres-vector psql -U postgres

Then enable the extension:

CREATE EXTENSION IF NOT EXISTS vector;

Next, create the table. The embedding dimensions must match your model, since Postgres rejects any other length, and all-MiniLM-L12-v2 produces 384:

CREATE TABLE movies (
  id bigserial PRIMARY KEY,
  title text NOT NULL,
  release_year int NOT NULL,
  origin text NOT NULL,
  genre text,
  plot text NOT NULL,
  embedding vector(384)
);

CREATE INDEX ON movies (title);

The title index lets us look up a movie by name later. Vector indexes support up to 2,000 dimensions, or 4,000 with halfvec.

Loading the Movie Data with Python

We’ll use the Wikipedia Movie Plots dataset, which has 34,886 movies with title, release year, origin, genre, and plot. A Hugging Face mirror needs no account. Keep psql open and use a second terminal:

curl -L -o wiki_movie_plots_deduped_with_summaries.csv \
  https://huggingface.co/datasets/vishnupriyavr/wiki-movie-plots-with-summaries/resolve/main/wiki_movie_plots_deduped_with_summaries.csv

Note: The plot text comes from Wikipedia and is licensed under CC BY-SA 4.0. The mirror also adds AI-generated plot summaries, which we don’t use.

This script removes duplicates and writes 33,833 movies to movies.jsonl. The model reads at most 128 tokens (about 100 words), so it adds a plot_start field with the first 60 words of each plot for us to embed.

prepare_movies.py
import csv
import json

csv.field_size_limit(10**9)  # some plots are very long

seen_plots, seen_titles = set(), set()
with open("wiki_movie_plots_deduped_with_summaries.csv", encoding="utf-8") as f, \
     open("movies.jsonl", "w", encoding="utf-8") as out:
    for row in csv.DictReader(f):
        title_year = (row["Title"], row["Release Year"])
        if row["Plot"] in seen_plots or title_year in seen_titles:
            continue  # skip duplicate rows
        seen_plots.add(row["Plot"])
        seen_titles.add(title_year)
        out.write(json.dumps({
            "title": row["Title"],
            "release_year": int(row["Release Year"]),
            "origin": row["Origin/Ethnicity"],
            "genre": row["Genre"],
            "plot": row["Plot"],
            # title + first 60 words fits the model's 128-token limit for all but 48 movies
            "plot_start": " ".join(row["Plot"].split()[:60]),
        }) + "\n")
python prepare_movies.py

Postgres stores vectors but doesn’t generate them, so we’ll use sentence-transformers, which runs the model locally. You need Python 3.11 or later, since PyTorch 2.15 does:

pip install sentence-transformers==6.3.0 "psycopg[binary]==3.3.9" pgvector==0.5.1

Note: On Linux, default PyTorch pulls in CUDA libraries (5.9 GB in our test, against 1.3 GB). Without a GPU, first run pip install torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu.

The loader embeds each title and plot_start, scaled to length 1 (normalize_embeddings=True), and inserts the rows.

load_movies.py
import json

import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

with open("movies.jsonl", encoding="utf-8") as f:
    movies = [json.loads(line) for line in f]

model = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2")
embeddings = model.encode(
    [f"{m['title']} {m['plot_start']}" for m in movies],
    batch_size=64,
    normalize_embeddings=True,
    show_progress_bar=True,
)

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as conn:
    register_vector(conn)
    with conn.cursor() as cur:
        cur.executemany(
            "INSERT INTO movies (title, release_year, origin, genre, plot, embedding) "
            "VALUES (%s, %s, %s, %s, %s, %s)",
            [(m["title"], m["release_year"], m["origin"], m["genre"], m["plot"], e)
             for m, e in zip(movies, embeddings)],
        )
python load_movies.py

Embedding 33,833 movies took between 5 and 6 minutes in Docker, on CPU.

Running a Semantic Search Query

To search, embed the query with the same model and sort by a distance operator. <=> is cosine distance, the usual choice for text. There’s also <-> (L2), <#> (negative inner product), and <+> (L1).

search_movies.py
import sys

import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2")
query_embedding = model.encode(sys.argv[1], normalize_embeddings=True)

with psycopg.connect("postgresql://postgres:postgres@localhost:5432/postgres") as conn:
    register_vector(conn)
    rows = conn.execute(
        """
        SELECT title, release_year, embedding <=> %(q)s AS distance
        FROM movies
        ORDER BY embedding <=> %(q)s
        LIMIT 5
        """,
        {"q": query_embedding},
    ).fetchall()

for title, year, distance in rows:
    print(f"{distance:.4f}  {title} ({year})")

Let’s search for the movie from the start of this guide:

python search_movies.py "the movie where the toys are alive when nobody is watching"
0.4851  Toy Story (1995)
0.5192  Silent Night, Deadly Night 5: The Toy Maker (1992)
0.5435   Jackass: The Movie (2002)
0.5442  All the Kind Strangers (1974)
0.5503  Tin Toy (1988)

Cosine distance runs from 0 to 2, so lower is closer. Jackass: The Movie in third is a fair reminder that “close in meaning” is the model’s opinion, not yours. “clownfish son captured by a diver” returns Finding Nemo first (0.5142), but the model only sees 60 words of each plot, so “child psychologist who has been dead the whole time” ranks The Sixth Sense 241st. Test with your users’ real queries.

Speeding Up pgvector with Indexes

Without an index, pgvector compares the query with every row. That’s exact, but slow as the table grows. An approximate nearest neighbor (ANN) index trades some recall (the share of true nearest neighbors it returns) for speed. pgvector has IVFFlat and HNSW.

Back in psql, our test query finds movies like The Matrix, using its embedding as the query:

SELECT title, release_year
FROM movies
ORDER BY embedding <=> (SELECT embedding FROM movies WHERE title = 'The Matrix')
LIMIT 5;
         title          | release_year
------------------------+--------------
 The Matrix             |         1999
 The Matrix Reloaded    |         2003
 The Matrix Revolutions |         2003
 Commando               |         1985
 Spy                    |         2015

We’ll time the top 10 with EXPLAIN ANALYZE, and index builds with \timing:

EXPLAIN (ANALYZE, COSTS OFF)
SELECT title, release_year
FROM movies
ORDER BY embedding <=> (SELECT embedding FROM movies WHERE title = 'The Matrix')
LIMIT 10;

Without an index, this scans all 33,833 rows in 17.0 ms. Postgres uses a vector index only for an ascending ORDER BY on a distance operator with a LIMIT.

IVFFlat

IVFFlat clusters vectors into lists with k-means and scans only the lists closest to the query, like a library that shelves books by topic. The docs suggest lists = rows / 1000 (up to 1M rows) and probes = sqrt(lists), which gives 34 and 6 for our table:

CREATE INDEX movies_embedding_ivfflat ON movies
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 34);

SET ivfflat.probes = 6;

The build took 0.5 seconds, and the same EXPLAIN now uses the index:

   ->  Index Scan using movies_embedding_ivfflat on movies (actual time=0.957..0.962 rows=10.00 loops=1)
 Execution Time: 0.970 ms

Build IVFFlat after loading data, since k-means needs real vectors (on a near-empty table, Postgres warns of low recall). Drop it before trying HNSW:

DROP INDEX movies_embedding_ivfflat;

HNSW

HNSW builds a multilayer graph, and a search works down from the sparse top layer, like taking highways first and local streets near your destination. It has no training step, so an empty table is fine. It builds faster when the graph fits in maintenance_work_mem. It took 5.0 seconds (and a notice) at the 64 MB default, and 3.1 at 512 MB:

SET maintenance_work_mem = '512MB';

CREATE INDEX movies_embedding_hnsw ON movies
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

SET hnsw.ef_search = 40;

m and ef_construction are the defaults. Keep hnsw.ef_search (the candidate list size, default 40) at least your LIMIT, since a plain HNSW scan returns at most that many candidates. Rerun the EXPLAIN:

   ->  Index Scan using movies_embedding_hnsw on movies (actual time=0.354..0.359 rows=10.00 loops=1)
 Execution Time: 0.364 ms

Checking Recall

To see how many of the true top 10 an index finds, compare it with an exact scan, where + 0 turns the sort key into an expression so Postgres can’t use the index:

WITH q AS (SELECT embedding FROM movies WHERE title = 'The Matrix'),
ann AS (
  SELECT id FROM movies
  ORDER BY embedding <=> (SELECT embedding FROM q)
  LIMIT 10
),
exact AS (
  SELECT id FROM movies
  ORDER BY (embedding <=> (SELECT embedding FROM q)) + 0
  LIMIT 10
)
SELECT count(*) AS matches FROM ann JOIN exact USING (id);

This returns 9 with HNSW, and gave 8 while the IVFFlat index existed (6 probes). Over 20 movies, HNSW’s recall was 0.95 at ef_search = 40 and 0.97 at 100. IVFFlat’s was 0.50, 0.85, and 0.92 at 1, 6, and 10 probes. Rebuilds shift these a little (6 to 8 for IVFFlat and 9 to 10 for HNSW over three builds), so check your own queries.

recall_20.sql
WITH queries AS (
  SELECT id, embedding FROM movies
  WHERE id % 1690 = 0  -- 20 movies spread across the table
)
SELECT round(avg((
  SELECT count(*) FROM (
    SELECT id FROM movies ORDER BY embedding <=> q.embedding LIMIT 10
  ) ann
  JOIN (
    SELECT id FROM movies ORDER BY (embedding <=> q.embedding) + 0 LIMIT 10
  ) exact USING (id)
)) / 10, 2) AS recall
FROM queries q;

IVFFlat vs HNSW

We measured each index’s size while it existed:

SELECT pg_size_pretty(pg_relation_size('movies_embedding_hnsw'));
IVFFlatHNSW
Build time0.5 s3.1 s (5.0 s at default memory)
Index size53 MB66 MB
Query time0.97 ms (probes = 6)0.36 ms (ef_search = 40)
Recall@100.850.95
Empty tableLow recallFine
Best forFrequent rebuilds, tight memoryMost workloads
Trade-offTune probes, build after loadingSlower build, bigger index

The raw vectors take 50 MB in pg_size_pretty units (33,833 × 384 × 4 bytes), so IVFFlat is little more than the vectors, and HNSW is a quarter larger. As the pgvector docs put it, HNSW has the better speed-recall trade-off but builds slower and uses more memory.

In short, HNSW gave better recall and faster queries at its defaults, and IVFFlat built faster and smaller but needed its probes tuned.

Filtering Vector Search Results

Most real searches add a filter, and this is where ANN indexes surprise you. Postgres applies WHERE after the index scan, so the HNSW index above (ef_search = 40) collects 40 candidates and the filter discards the rest. British movies are 10% of the table:

SELECT title, release_year
FROM movies
WHERE origin = 'British'
ORDER BY embedding <=> (SELECT embedding FROM movies WHERE title = 'The Matrix')
LIMIT 10;

We got back only 3 rows (3 to 5 over three builds, close to the 4 the pgvector docs predict). pgvector 0.8.0 added iterative index scans, which keep scanning until enough rows match or hnsw.max_scan_tuples (20,000 by default) is reached:

SET hnsw.iterative_scan = strict_order;

Now it returns 10 rows, but only 6 are in the exact top 10. For exact results, use the + 0 trick, at sequential-scan speed unless you index the filter column. A partial index also works for a few filter values, and partitioning for many (like tenants).

Running pgvector in Production

The big win with pgvector over a separate vector database is that vectors live next to your data, with the transactions, backups, and replication you already run. A few things are on you:

  • The embedding pipeline. Every insert, text update, and text query needs a call to the model, and switching models means re-embedding every row.
  • Index memory. Indexes don’t have to fit in RAM, but they perform better when they do.
  • Hybrid search with pgvector. Blending keyword and vector results means running a tsvector query and a pgvector query and merging them yourself, for example with Reciprocal Rank Fusion. Typo tolerance needs yet another extension, like pg_trgm.

An Alternative Approach: Purpose-Built Search Engines

For user-facing search, vector similarity is only part of the job. Users also expect keyword matches, typo tolerance, and facet counts, which are separate pieces in Postgres. Purpose-built search engines like Typesense generate the embeddings from the schema and handle all of it in one request.

Vector Search in Typesense

Start Typesense (or use Typesense Cloud):

docker run -d --name typesense -p 127.0.0.1:8108:8108 \
  typesense/typesense:30.2 --data-dir /tmp --api-key=xyz

Create a collection whose embedding field the built-in ts/all-MiniLM-L12-v2 model builds from title and plot_start:

curl -fsS 'http://localhost:8108/collections' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "movies",
    "fields": [
      { "name": "title", "type": "string" },
      { "name": "origin", "type": "string", "facet": true },
      { "name": "plot", "type": "string" },
      { "name": "plot_start", "type": "string" },
      {
        "name": "embedding",
        "type": "float[]",
        "embed": {
          "from": ["title", "plot_start"],
          "model_config": { "model_name": "ts/all-MiniLM-L12-v2" }
        }
      }
    ]
  }'

Then import the same movies.jsonl, and Typesense embeds each document:

curl -fsS 'http://localhost:8108/collections/movies/documents/import?action=create' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  --data-binary @movies.jsonl | grep -c '"success":true'

It printed 33833 after about 4 minutes in Docker, on CPU, and the vectors matched pgvector’s (cosine similarity 1.000000 on the 21 movies we checked). Next, run the toys query as a semantic search:

curl -fsS -G 'http://localhost:8108/collections/movies/documents/search' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  --data-urlencode 'q=the movie where the toys are alive when nobody is watching' \
  --data-urlencode 'query_by=embedding' \
  --data-urlencode 'include_fields=title' \
  --data-urlencode 'per_page=5'
{ "hits": [
  { "document": { "title": "Toy Story" }, "vector_distance": 0.4850881099700928 },
  { "document": { "title": "Silent Night, Deadly Night 5: The Toy Maker" }, "vector_distance": 0.5191624164581299 },
  { "document": { "title": "All the Kind Strangers" }, "vector_distance": 0.5441535711288452 },
  { "document": { "title": "Tin Toy" }, "vector_distance": 0.5503048896789551 },
  { "document": { "title": "Where the Toys Come From" }, "vector_distance": 0.5651594400405884 }
] }

The distances match pgvector’s, but Jackass: The Movie is missing, since Typesense’s index is HNSW too and its search width, ef, defaults to 10 (pgvector’s is 40). vector_query=embedding:([], ef:200) returns pgvector’s exact top 5.

Then find the 10 British movies closest to The Matrix (id: 13419, since Typesense numbers documents in import order), with ef: 40 to match pgvector:

curl -fsS -G 'http://localhost:8108/collections/movies/documents/search' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  --data-urlencode 'q=*' \
  --data-urlencode 'filter_by=origin:British' \
  --data-urlencode 'vector_query=embedding:([], id: 13419, ef: 40)' \
  --data-urlencode 'include_fields=title' \
  --data-urlencode 'per_page=10'
{ "found": 10 }

All 10 come back, and 9 or 10 are in the exact top 10 (over three builds), against 6 for pgvector’s iterative scan.

Hybrid Search in One Request

For hybrid search, list text fields and the embedding field in query_by, and Typesense merges keyword and vector results with rank fusion:

curl -fsS -G 'http://localhost:8108/collections/movies/documents/search' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  --data-urlencode 'q=clownfish son captured by a diver' \
  --data-urlencode 'query_by=title,plot,embedding' \
  --data-urlencode 'facet_by=origin' \
  --data-urlencode 'include_fields=title' \
  --data-urlencode 'per_page=2'
{ "hits": [
  { "document": { "title": "Finding Nemo" }, "text_match": 3467833264251603057, "hybrid_search_info": { "rank_fusion_score": 1.0 } },
  { "document": { "title": "Humanoids from the Deep" }, "text_match": 0, "hybrid_search_info": { "rank_fusion_score": 0.15000000596046448 } }
] }

Finding Nemo tops both lists, Humanoids from the Deep comes from the vector side alone (text_match is 0), and facet_by counts origins for all 100 matches. Misspell clownfish as clownfsh, and pgvector drops Finding Nemo to 104th, while Typesense’s keyword side, with typo tolerance, keeps it first.

Rank fusion weights keywords 0.7 and vectors 0.3 by default, so for the toys query, a loose keyword match on Mr. Nobody beats Toy Story. alpha raises the vector weight:

curl -fsS -G 'http://localhost:8108/collections/movies/documents/search' \
  -H 'X-TYPESENSE-API-KEY: xyz' \
  --data-urlencode 'q=the movie where the toys are alive when nobody is watching' \
  --data-urlencode 'query_by=title,plot,embedding' \
  --data-urlencode 'vector_query=embedding:([], alpha: 0.8)' \
  --data-urlencode 'include_fields=title' \
  --data-urlencode 'per_page=2'
{ "hits": [
  { "document": { "title": "Toy Story" }, "hybrid_search_info": { "rank_fusion_score": 0.800000011920929 } },
  { "document": { "title": "Silent Night, Deadly Night 5: The Toy Maker" }, "hybrid_search_info": { "rank_fusion_score": 0.4000000059604645 } }
] }

There are trade-offs. Typesense keeps its index in RAM (the process allocated about 650 MB after the import) and isn’t a primary data store, so Postgres stays the source of truth and you sync to it. Built-in models run on CPU unless you add a GPU.

Conclusion

pgvector is a great choice for vector search inside the Postgres database you already run. Start with HNSW, set ef_search from a recall check on your own queries, and turn on iterative scans once you add filters.

If you’re building user-facing search that also needs typo tolerance, faceting, and hybrid ranking, a purpose-built search engine like Typesense can generate the embeddings and combine keyword and vector ranking in one request, at the cost of a second system to keep in sync with Postgres.