{"slug": "hybrid-search-in-postgres-when-embeddings-miss-the-exact-match", "title": "Hybrid Search in Postgres: When Embeddings Miss the Exact Match", "summary": "Postgres can run keyword and vector search in one query and fuse the results with reciprocal rank fusion (RRF), avoiding a second database or reranking service when embeddings miss exact strings like error codes or SKUs, according to a guide following Supabase's hybrid search documentation. The approach stores a generated tsvector column with a GIN index and a pgvector embedding column with an HNSW index, then merges the two ranked lists in a hybrid_search SQL function using score(doc) = Σ 1/(k + rank_in_list), with k defaulting to 50 in Supabase's reference implementation versus 60 in the original RRF paper. A full outer join ensures documents found by only one search still appear in the final results, and each CTE pulls twice as many candidates as requested, capped at 30.", "body_md": "You ship a RAG feature, it demos beautifully, and then a user pastes `ERR_SSL_PROTOCOL_ERROR` into the search box. The top result is a vaguely related page about TLS certificates. The page that literally contains that error string is ranked eleventh. Nothing is broken. Embeddings are doing exactly what they were built to do: matching *meaning*. An error code, a SKU, a function name, or a person's surname has very little meaning to match on.\n\nThe fix most teams reach for is a second database or a reranking service. Before you do that, know that Postgres can run both kinds of search and merge them in a single query.\n\n## Two searches, two blind spots \n\nKeyword search and semantic search fail in opposite directions.\n\n- **Full-text search** (Postgres`tsvector` ) is great at exact tokens. Search \"invoice 4471\" and it finds the document with \"invoice 4471\" in it. It is bad at synonyms: \"cancel my plan\" won't find a doc titled \"Ending your subscription.\"\n- **Vector search** (pgvector) is great at paraphrase. It finds \"Ending your subscription\" for \"cancel my plan.\" It is unreliable on rare literal strings, because those tokens barely move an embedding.\n\nHybrid search runs both and fuses the results. The tricky part is the fusion. A `ts_rank_cd` score and a cosine distance are on completely different scales, so you can't add them up. Reciprocal rank fusion (RRF) sidesteps that by ignoring the scores and using only each document's **position** in each list:\n\n```\nscore(doc) = Σ  1 / (k + rank_in_list)\n```\n\nA document ranked 1st in keyword search and 4th in vector search scores `1/(k+1) + 1/(k+4)`. A document found by only one search gets nothing from the other. `k` is a smoothing constant that keeps a single #1 ranking from swamping everything else. The original RRF paper used 60. Supabase's reference implementation defaults to 50. Either is a sane start.\n\n## The schema and the function \n\nThis follows the pattern in [Supabase's hybrid search guide](https://supabase.com/docs/guides/ai/hybrid-search), adjusted to use cosine distance. It runs on any Postgres with the `vector` extension.\n\n```\ncreate extension if not exists vector;\n\ncreate table documents (\n  id bigint primary key generated always as identity,\n  content text not null,\n  fts tsvector generated always as (to_tsvector('english', content)) stored,\n  embedding vector(512)\n);\n\ncreate index on documents using gin (fts);\ncreate index on documents using hnsw (embedding vector_cosine_ops);\n```\n\nThe `fts` column is generated, so it never drifts out of sync with `content`. The HNSW index operator class has to match the distance operator you query with: `vector_cosine_ops` pairs with `<=>`.\n\n```\ncreate or replace function hybrid_search(\n  query_text text,\n  query_embedding vector(512),\n  match_count int,\n  full_text_weight float = 1,\n  semantic_weight float = 1,\n  rrf_k int = 50\n)\nreturns setof documents\nlanguage sql\nas $$\nwith full_text as (\n  select id,\n    row_number() over (\n      order by ts_rank_cd(fts, websearch_to_tsquery(query_text)) desc\n    ) as rank_ix\n  from documents\n  where fts @@ websearch_to_tsquery(query_text)\n  order by rank_ix\n  limit least(match_count, 30) * 2\n),\nsemantic as (\n  select id,\n    row_number() over (order by embedding <=> query_embedding) as rank_ix\n  from documents\n  order by rank_ix\n  limit least(match_count, 30) * 2\n)\nselect documents.*\nfrom full_text\nfull outer join semantic on full_text.id = semantic.id\njoin documents on coalesce(full_text.id, semantic.id) = documents.id\norder by\n  coalesce(1.0 / (rrf_k + full_text.rank_ix), 0.0) * full_text_weight +\n  coalesce(1.0 / (rrf_k + semantic.rank_ix), 0.0) * semantic_weight\n  desc\nlimit least(match_count, 30)\n$$;\n```\n\nThe `full outer join` is the important bit: a document that only one search found still makes it into the final list. `websearch_to_tsquery` accepts the kind of input users actually type (quoted phrases, `-exclusions`) without throwing a syntax error. Each CTE pulls twice as many candidates as you return, so fusion has some room to reorder.\n\n## Calling it from Node \n\nEmbed the query with the same model and dimension count you used for the documents, then pass both the raw text and the vector:\n\n``` python\nimport OpenAI from \"openai\";\nimport pg from \"pg\";\n\nconst openai = new OpenAI();\nconst pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });\n\nexport async function search(query: string, limit = 10) {\n  const { data } = await openai.embeddings.create({\n    model: \"text-embedding-3-small\",\n    input: query,\n    dimensions: 512,\n  });\n\n  // pgvector accepts the '[0.1,0.2,...]' text format, which JSON.stringify produces\n  const { rows } = await pool.query(\n    \"select id, content from hybrid_search($1, $2::vector, $3)\",\n    [query, JSON.stringify(data[0].embedding), limit],\n  );\n  return rows;\n}\n```\n\n## Where it gets harder \n\nHybrid search is not free. You now pay for two index scans per query, and `ts_rank_cd` can't use the GIN index for ranking, only for filtering. That is fine for a few hundred matches and slow for a few hundred thousand, so keep that `where` clause selective.\n\nThe weights are tuning knobs, not magic. If your users mostly paste identifiers, raise `full_text_weight`. If they ask questions in plain language, raise `semantic_weight`. Don't guess: put 30 real queries with known-good answers in a test file and measure which settings put the right document in the top five.\n\nAlso be clear about when you don't need this at all. If your search box is for product codes or log lines, plain full-text search is simpler and better. If your corpus is short, conversational answers, vectors alone may be fine. Hybrid search earns its keep when your users type both kinds of query and you can't predict which.\n\n## The takeaway \n\nWhen retrieval misses an obvious exact match, the problem usually isn't your chunking or your embedding model. The real issue is asking a meaning-based index to do a string-matching job. Add a generated `tsvector` column, fuse the two rankings with RRF, and let Postgres handle both. You get the exact-match recall of keyword search and the paraphrase tolerance of embeddings without another service to run.", "url": "https://wpnews.pro/news/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match", "canonical_source": "https://danholloran.me/posts/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match", "published_at": "2026-11-28 10:15:33+00:00", "updated_at": "2026-11-29 15:45:39.648774+00:00", "lang": "en", "topics": ["ai-search", "artificial-intelligence"], "entities": ["Postgres", "Supabase", "pgvector", "reciprocal rank fusion"], "also_reported_by": [], "takeaway": "Fuse Postgres full-text (ts_rank_cd) and pgvector cosine results with reciprocal rank fusion using k=50 and a full outer join, so a document found by only one search still reaches the final list.", "recommendation": {"advice": "Add a generated tsvector column with a GIN index alongside your pgvector HNSW index and merge both ranked lists with RRF (k=50) via a full outer join to catch exact error codes and SKUs embeddings miss.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match", "markdown": "https://wpnews.pro/news/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match.md", "text": "https://wpnews.pro/news/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match.txt", "jsonld": "https://wpnews.pro/news/hybrid-search-in-postgres-when-embeddings-miss-the-exact-match.jsonld"}}