From the blog

pgvector HNSW Index in Elixir: Tune Vector Search in Phoenix with Ecto

By Liam Killingback ·

pgvector HNSW Index in Elixir: Tune Vector Search in Phoenix with Ecto

Most Elixir RAG tutorials, ours included, add a pgvector HNSW index in one line and move on. That line is fine for the first ten thousand chunks. Then the table grows, a filter gets added to the query, and one of three things happens: searches slow down because Postgres quietly stopped using the index, results get worse because the index is returning fewer good neighbours than you think, or a deploy hangs for twenty minutes while a migration builds the index under a table lock.

This guide is the part the one-liner skips. It covers how the pgvector HNSW index works in an Elixir and Phoenix app, how to build it safely from an Ecto migration, which of the three tuning knobs matter, how to measure recall instead of guessing, and what to do when a where clause ruins your results. It follows on from RAG in Elixir with pgvector and Postgres, and it assumes you already have a document_chunks table with an embedding column and the pgvector Hex package installed.

Exact search, and why you eventually leave it

Without an index, a nearest-neighbour query is exact. Postgres computes the distance from your query vector to every row, sorts, and returns the top results. That is perfect recall, and the cost grows in a straight line with the table.

import Ecto.Query
import Pgvector.Ecto.Query

def nearest(vector, k \\ 8) do
  from(c in DocumentChunk,
    order_by: cosine_distance(c.embedding, ^Pgvector.new(vector)),
    limit: ^k
  )
  |> Repo.all()
end

Be honest about your size before adding anything. A few tens of thousands of 1,536-dimension vectors scan in tens of milliseconds, and if every query filters to one customer’s few thousand rows with a normal B-tree index, exact search may be all you ever need. An approximate index trades a little recall for a lot of speed. Do not pay the recall until you need the speed.

HNSW vs IVFFlat in one table

pgvector ships two approximate index types.

HNSW IVFFlat
Structure A layered graph of neighbours Vectors bucketed into lists around centroids
Query speed at the same recall Better Worse
Build time Slower Faster
Memory and disk Larger Smaller
Needs data before building No Yes (centroids are trained on existing rows)
Copes with data that keeps changing Well Recall drifts until you reindex
Query-time knob hnsw.ef_search ivfflat.probes

For an app that ingests documents continuously, which is nearly every Phoenix RAG app, HNSW is the default choice: you can create it on an empty table and it stays good as rows arrive. IVFFlat is worth a look when build time or memory is the constraint and the data is loaded in bulk. If you do use it, the pgvector guidance is lists = rows / 1000 up to a million rows and sqrt(rows) beyond that, with probes near sqrt(lists).

The rest of this guide is about HNSW.

Build the index without locking the table

A plain CREATE INDEX blocks writes to the table until it finishes. On an empty table that takes no time. On two million chunks it is long enough to fail your deploy’s health checks. Build it concurrently, which means the migration cannot run inside a transaction:

defmodule MyApp.Repo.Migrations.AddChunksHnswIndex do
  use Ecto.Migration

  @disable_ddl_transaction true
  @disable_migration_lock true

  def up do
    execute("""
    CREATE INDEX CONCURRENTLY document_chunks_embedding_hnsw
    ON document_chunks
    USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64)
    """)
  end

  def down do
    execute("DROP INDEX CONCURRENTLY IF EXISTS document_chunks_embedding_hnsw")
  end
end

Four things to know about this migration.

The operator class must match your query. vector_cosine_ops serves cosine_distance (the <=> operator). If you query with l2_distance or max_inner_product, the index needs vector_l2_ops or vector_ip_ops. A mismatch is not an error. Postgres just ignores the index and scans the table.

A failed concurrent build leaves an invalid index behind. If the build is interrupted, the index exists but is marked invalid and is never used. Drop it and run the migration again. This is also why the example does not use IF NOT EXISTS: that would skip straight past the broken one.

Give the build memory. HNSW builds are dramatically faster when the graph fits in maintenance_work_mem, and they can use parallel workers (max_parallel_maintenance_workers). Because this migration runs outside a transaction, a SET in one execute is not guaranteed to be on the same pooled connection as the next, so set these on the role that runs migrations instead:

ALTER ROLE my_app SET maintenance_work_mem = '2GB';
ALTER ROLE my_app SET max_parallel_maintenance_workers = 4;

Reset them afterwards if the same role serves your app. You can watch progress from another session with SELECT phase, tuples_done, tuples_total FROM pg_stat_progress_create_index.

Bulk load first, index second. If you are backfilling a large corpus, insert the rows and then build the index. Inserting into an existing HNSW index is much slower per row than building once over the finished table.

The three knobs

HNSW has two build-time parameters and one query-time parameter.

  • m (default 16) is the number of connections each node keeps per layer. More connections mean better recall on hard datasets, a bigger index and slower builds.
  • ef_construction (default 64) is how many candidates the build considers when wiring each node. Higher values produce a better graph and a slower build. It must be at least twice m.
  • hnsw.ef_search (default 40) is how many candidates a query keeps while walking the graph. Higher values raise recall and latency together.

The practical advice is short. Leave m and ef_construction at their defaults until measurement tells you otherwise, because changing them means rebuilding the index. Tune ef_search first, because it is a per-query setting you can change in a second.

One rule is easy to miss: without iterative scans (covered below), a query returns at most ef_search rows. If you ask for limit: 100 with the default of 40, you get 40. Retrieval that fetches a wide candidate set for a reranker hits this immediately.

Set ef_search per query from Ecto

ef_search is a Postgres setting, and a setting belongs to a connection. With a connection pool you cannot run SET and then run the query, because the two statements may use different connections. SET LOCAL inside a transaction solves it: the setting applies to that transaction only and is gone when it commits.

defmodule MyApp.Knowledge.Search do
  import Ecto.Query
  import Pgvector.Ecto.Query

  alias MyApp.Repo
  alias MyApp.Knowledge.DocumentChunk

  def nearest(vector, opts \\ []) do
    k = Keyword.get(opts, :limit, 8)
    ef = opts |> Keyword.get(:ef_search, max(k, 80)) |> validate_ef!()

    query =
      from c in DocumentChunk,
        order_by: cosine_distance(c.embedding, ^Pgvector.new(vector)),
        limit: ^k

    {:ok, rows} =
      Repo.transaction(fn ->
        Repo.query!("SET LOCAL hnsw.ef_search = #{ef}")
        Repo.all(query)
      end)

    rows
  end

  defp validate_ef!(ef) when is_integer(ef) and ef in 1..1000, do: ef
end

SET does not accept bind parameters, so the value is interpolated into the SQL. That is why validate_ef!/1 exists: it only lets an integer in pgvector’s allowed range through, so nothing a user typed can ever reach that string.

Measure recall instead of guessing

Recall is the share of the true nearest neighbours that the index returned. You can measure it on your own data in a few lines, because Postgres will run the same query exactly if you tell it not to use the index:

defmodule MyApp.Knowledge.Recall do
  import Ecto.Query
  import Pgvector.Ecto.Query

  alias MyApp.Repo
  alias MyApp.Knowledge.DocumentChunk

  @doc "Average recall@k of the HNSW index over a list of sample query vectors."
  def measure(sample_vectors, k \\ 10, ef_search \\ 40) do
    scores =
      for vector <- sample_vectors do
        exact = ids(vector, k, "SET LOCAL enable_indexscan = off")
        approx = ids(vector, k, "SET LOCAL hnsw.ef_search = #{ef_search}")
        MapSet.size(MapSet.intersection(exact, approx)) / max(MapSet.size(exact), 1)
      end

    Enum.sum(scores) / length(scores)
  end

  defp ids(vector, k, setting) do
    query =
      from c in DocumentChunk,
        order_by: cosine_distance(c.embedding, ^Pgvector.new(vector)),
        limit: ^k,
        select: c.id

    {:ok, ids} =
      Repo.transaction(fn ->
        Repo.query!(setting)
        Repo.all(query)
      end)

    MapSet.new(ids)
  end
end

Feed it real queries, not random vectors. A hundred questions pulled from your logs, embedded once and saved to a file, make a good fixture. Then sweep:

for ef <- [20, 40, 80, 160, 320] do
  {ef, MyApp.Knowledge.Recall.measure(samples, 10, ef)}
end

You will see recall climb and then flatten. Pick the smallest ef_search on the flat part, check its latency, and write the number down next to the date and the row count. If recall is poor even at high ef_search, that is the signal to rebuild with a larger m and ef_construction. Run the same sweep after any change to the embedding model or the chunking, since both change the shape of the data.

Why Postgres is not using your index

When a vector query is slow, check the plan before touching any knob:

Repo.explain(:all, query, analyze: true) |> IO.puts()

You are looking for Index Scan using document_chunks_embedding_hnsw. If you see Seq Scan and a Sort, it is usually one of these:

  1. No limit. The index is only considered for ORDER BY distance LIMIT k.
  2. The order is not a bare distance. order_by: cosine_distance(...) uses the index. Ordering by a similarity you computed, such as 1 - distance, or ordering descending, does not. Order by distance ascending and convert to a similarity in select if you want one.
  3. The operator does not match the operator class, as described above.
  4. Too many dimensions. A vector column can be HNSW-indexed up to 2,000 dimensions. text-embedding-3-large produces 3,072, so the index creation fails. Either request shorter vectors with the API’s dimensions option, or index a half-precision cast, which supports up to 4,000 dimensions and halves the index size:
CREATE INDEX CONCURRENTLY document_chunks_embedding_hnsw
ON document_chunks
USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);

The query must then order by the same cast expression, which in Ecto means a fragment("?::halfvec(3072) <=> ?::halfvec(3072)", c.embedding, ^Pgvector.new(vector)).

  1. The planner decided a scan was cheaper. On a small table it is right. Do not fight it.

The filter problem

This is the failure that surprises people most. Take a filtered search:

from c in DocumentChunk,
  where: c.org_id == ^org_id,
  order_by: cosine_distance(c.embedding, ^Pgvector.new(vector)),
  limit: 8

The HNSW index knows nothing about org_id. Postgres walks the graph, collects ef_search candidates across every organisation, and applies the where afterwards. If this organisation owns 5% of the table, the default 40 candidates leave about two rows. The query asked for eight and got two, with no error.

There are three fixes, and the right one depends on how selective the filter is.

Iterative scans (pgvector 0.8 and later) keep walking the graph until enough rows pass the filter:

Repo.transaction(fn ->
  Repo.query!("SET LOCAL hnsw.iterative_scan = relaxed_order")
  Repo.query!("SET LOCAL hnsw.max_scan_tuples = 20000")
  Repo.all(query)
end)

relaxed_order is faster and may return rows slightly out of distance order, which is fine if you sort the handful of results in Elixir afterwards. strict_order keeps exact ordering. max_scan_tuples caps how far the scan may go.

Partial indexes suit a filter with few, fixed values: CREATE INDEX ... USING hnsw (embedding vector_cosine_ops) WHERE kind = 'faq'. Each partial index is its own small graph, so recall inside it is unaffected by the rest of the table.

Exact search behind a B-tree suits very selective filters. If the filter narrows the table to a few thousand rows, a normal index on org_id plus an exact distance sort is both faster and perfectly accurate. With a per-tenant where clause this is often the real answer, and our guide to multi-tenant RAG in Elixir goes through that design, including how to keep one customer’s chunks out of another’s results.

Keep it healthy in production

Size it. A 1,536-dimension vector is about 6 KB, so a million chunks is roughly 6 GB of vectors before the graph’s own links. HNSW is fast when the index sits in memory and slow when it does not. Check what you have:

Repo.query!("SELECT pg_size_pretty(pg_relation_size('document_chunks_embedding_hnsw'))")

If the index is outgrowing RAM, half-precision vectors (halfvec) cut it roughly in half for a small recall cost that your recall script can now measure.

Expect slower writes. Each insert walks the graph to wire the new node in. Embedding calls dominate ingestion time in practice, but batch your inserts and keep ingestion in background jobs so a bulk upload never competes with requests for the pool.

Reindex after heavy churn. Deleting or re-embedding a large share of rows leaves dead entries that vacuum is slow to clear from a graph. After a big cleanup, REINDEX INDEX CONCURRENTLY document_chunks_embedding_hnsw rebuilds it without blocking.

Alert on latency, not on faith. Wrap the search in a :telemetry.span/3 and chart the p95. A sudden jump almost always means the plan changed or the index no longer fits in memory.

A sane default recipe

If you want the short version:

  1. Under roughly 50,000 rows, or when every query filters to a small tenant, use exact search and a B-tree on the filter column.
  2. Otherwise create an HNSW index concurrently with the default m = 16, ef_construction = 64 and the operator class that matches your query.
  3. Set ef_search per query with SET LOCAL, starting around 80, and never below your limit.
  4. Measure recall on real queries and pick the smallest ef_search on the flat part of the curve.
  5. For filtered queries, turn on iterative scans, or switch to partial indexes or exact search depending on selectivity.
  6. Re-measure whenever the embedding model, the chunking or the table size changes by a lot.

Skip the plumbing

Index tuning is the last 10% of a retrieval feature. The first 90% is ingestion, chunking, embedding, the search query and a LiveView that streams the answer. If you would rather start from that already working, pdfai is a Phoenix app that reads documents, embeds them into pgvector and answers questions over them, so you can spend your time on recall and product instead of wiring. Combining vector search with keyword search is the usual next step, and hybrid search in Elixir covers it.

PhxTemplates is the AI-native, use-case-specific Phoenix starter, at a lifetime price. The Builder Pass unlocks every template, including the AI ones, for a single payment.

Wrapping up

The pgvector HNSW index in Elixir is one line to create and a handful of decisions to run well. Build it concurrently so deploys stay boring, match the operator class to the query, and treat ef_search as the dial you turn per query through SET LOCAL. Measure recall with the exact-search trick so every setting is backed by a number from your own data. And when a filter is involved, remember that the graph cannot see your where clause: use iterative scans, a partial index, or plain exact search over a small filtered set. All of it is ordinary Ecto and ordinary Postgres, which is the reason to keep your vectors there in the first place.