Your users type "invoice not sending" and the help centre returns nothing, because the article is titled "Troubleshooting email delivery failures." Or they search for error code E4021 and a semantic search returns five loosely related articles but not the one that contains that exact code. Both failures are common, and neither keyword search nor vector search alone fixes them.
This guide shows how to build an AI search system that combines both: PostgreSQL full-text search, pgvector semantic search, a rank-fusion step and an optional reranker, with a Node.js API on top. It also covers how to measure whether your search is actually good, which is the part most tutorials skip.
Direct answer: how do you build AI-powered search?
- Run two retrievers: keyword search (BM25-style or Postgres full-text) for exact terms, and vector search for meaning.
- Merge the two ranked lists with a simple method such as reciprocal rank fusion (RRF).
- Optionally rerank the top candidates with a reranker model for better ordering.
- Measure with a labelled query set (recall@k, MRR) and iterate. Without evaluation you cannot tell an improvement from a regression.
Table of contents
- Why keyword search and semantic search both fail alone
- Architecture of a hybrid AI search system
- Step 1: Schema for keyword and vector search
- Step 2: Two retrievers in Node.js
- Step 3: Merge results with reciprocal rank fusion
- Step 4: Rerank and filter
- How do you evaluate search quality?
- Production considerations
- Common mistakes
- Best practices
- Frequently asked questions
- Conclusion
- References
Why keyword search and semantic search both fail alone
Keyword search matches the tokens users type. It is precise for part numbers, error codes and names, and it is fast and explainable. It misses synonyms and paraphrases ("cheap" versus "budget").
Semantic (vector) search matches meaning through embeddings (how vector databases work). It handles paraphrases and natural-language questions, but can be weak on rare exact tokens and sometimes returns "related but wrong" results with high confidence.
Hybrid search combines them so each covers the other's blind spots. It is not a magic upgrade: it adds a second index, a merge step and more to evaluate. Use it when your content has both exact identifiers and natural-language intent, which covers most product documentation, catalogues and support content.
Architecture of a hybrid AI search system
flowchart TD
Q[User query] --> N[Normalize and embed query]
N --> K[Keyword search: Postgres full-text]
N --> V[Vector search: pgvector]
K --> F[Rank fusion: RRF]
V --> F
F --> P[Optional reranker on top candidates]
P --> R[Results with snippets and filters]
subgraph Indexing
D[Content change] --> C[Chunk and embed]
C --> DB[(Postgres: text, tsvector, vector, metadata)]
end
DB --> K
DB --> VKeeping both indexes in one Postgres database has a real benefit: tenant filters, permissions and freshness are handled in a single place. If your scale or latency needs later outgrow it, the architecture stays the same and the retrievers become separate services.
Step 1: Schema for keyword and vector search
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE docs (
id bigserial PRIMARY KEY,
tenant_id integer NOT NULL,
title text NOT NULL,
body text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
embedding vector(1536) NOT NULL,
-- generated column keeps the keyword index in sync automatically
tsv tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', body), 'B')
) STORED
);
CREATE INDEX docs_tsv_idx ON docs USING gin (tsv);
CREATE INDEX docs_embedding_idx ON docs USING hnsw (embedding vector_cosine_ops);
CREATE INDEX docs_tenant_idx ON docs (tenant_id);
Title matches are weighted higher ('A') than body matches ('B'), which usually matches user expectations. The GENERATED ... STORED column means you never forget to update the keyword index when the text changes. For more on Postgres search and indexing, see full-text search in PostgreSQL and indexes and EXPLAIN ANALYZE.
Step 2: Two retrievers in Node.js
// retrievers.mjs (example code; add error handling, timeouts and pooling config for production)
import pg from "pg";
import OpenAI from "openai";
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const openai = new OpenAI();
export async function embedQuery(q) {
const res = await openai.embeddings.create({ model: "text-embedding-3-small", input: q });
return JSON.stringify(res.data[0].embedding);
}
export async function keywordSearch(tenantId, q, limit = 30) {
const { rows } = await pool.query(
`SELECT id, title, ts_rank_cd(tsv, query) AS score
FROM docs, websearch_to_tsquery('english', $2) AS query
WHERE tenant_id = $1 AND tsv @@ query
ORDER BY score DESC
LIMIT $3`,
[tenantId, q, limit],
);
return rows;
}
export async function vectorSearch(tenantId, vector, limit = 30) {
const { rows } = await pool.query(
`SELECT id, title, embedding <=> $2::vector AS distance
FROM docs
WHERE tenant_id = $1
ORDER BY embedding <=> $2::vector
LIMIT $3`,
[tenantId, vector, limit],
);
return rows;
}
websearch_to_tsquery accepts the way people actually type (quoted phrases, -exclude, or) and does not throw on odd input the way to_tsquery can. Both queries are parameterised, which prevents SQL injection from user search text. Never interpolate the query into SQL strings.
Step 3: Merge results with reciprocal rank fusion
The two retrievers return scores on different scales (a ts_rank number and a cosine distance), so you cannot add them directly. Reciprocal rank fusion sidesteps this by using only ranks: each document scores 1 / (k + rank) in every list where it appears, and the scores are summed. The constant k (commonly 60 in the original paper) damps the influence of top ranks.
// fusion.mjs
export function rrf(lists, k = 60) {
const scores = new Map();
for (const list of lists) {
list.forEach((item, index) => {
const entry = scores.get(item.id) ?? { ...item, rrf: 0 };
entry.rrf += 1 / (k + index + 1);
scores.set(item.id, entry);
});
}
return [...scores.values()].sort((a, b) => b.rrf - a.rrf);
}
// search-api.mjs
import { keywordSearch, vectorSearch, embedQuery } from "./retrievers.mjs";
import { rrf } from "./fusion.mjs";
export async function hybridSearch(tenantId, q, limit = 10) {
const vector = await embedQuery(q);
const [kw, vec] = await Promise.all([keywordSearch(tenantId, q), vectorSearch(tenantId, vector)]);
return rrf([kw, vec]).slice(0, limit);
}
console.log(await hybridSearch(1, "invoice not sending"));
Running the two retrievers concurrently with Promise.all keeps total latency near the slower of the two rather than the sum (see async JavaScript). For the query "error E4021", the keyword list ranks the page containing that exact code first, the vector list ranks conceptually related pages, and fusion puts the page that appears high in both at the top.
RRF's appeal is that it needs no tuning of score weights. Its limit is that it ignores how much better one result is than another. If you need weighting, add per-retriever multipliers and validate them on your evaluation set, not by feel.
Step 4: Rerank and filter
Fusion gives a good candidate set; a reranker can improve its order. A reranker (often a cross-encoder or an LLM-based scorer) reads the query and each candidate together, which is more accurate than comparing precomputed vectors, but slower and costlier. The usual pattern is to retrieve 30–50 candidates cheaply, then rerank only the top 20 or so and return 10.
Because reranking adds latency and cost, apply it only if your evaluation shows a meaningful gain. Some provider and open-source rerankers exist; check the current documentation of the one you pick rather than assuming an API.
Practical filtering rules:
- Permissions in SQL, not after. Filter by tenant and access level in the
WHEREclause so a user can never receive a snippet they should not see. - Relevance cut-off. If the best vector distance is poor and no keyword hits exist, return "no results" rather than the least-bad guess.
- Snippets. Use
ts_headlinefor highlighted snippets of keyword matches so users see why a result matched.
How do you evaluate search quality?
Build a small labelled set: 50 to 200 real queries, each with the document ids that should be found. Then compute standard measures:
- Recall@k: the share of queries where at least one correct document is in the top k.
- MRR (mean reciprocal rank): the average of
1 / rank of the first correct result. - nDCG, if you have graded relevance labels.
// eval.mjs: recall@k and MRR over a labelled set
export async function evaluate(cases, searchFn, k = 10) {
let hits = 0, rr = 0;
for (const { tenantId, query, relevantIds } of cases) {
const results = await searchFn(tenantId, query, k);
const rank = results.findIndex((r) => relevantIds.includes(Number(r.id)));
if (rank !== -1) { hits++; rr += 1 / (rank + 1); }
}
return { recallAtK: hits / cases.length, mrr: rr / cases.length };
}
Run it for keyword-only, vector-only and hybrid. Whichever wins on your data wins; do not assume hybrid always does. Add real zero-result and low-click queries from your logs to the set over time. Track click-through and reformulation rate in production as a second signal.
Production considerations
- Latency budget. Embedding the query is an API call. Cache embeddings for frequent queries and set timeouts so a slow embedding call degrades to keyword-only search instead of failing. See caching strategies.
- Freshness. Re-embed and update rows on content change. A queue-driven indexer is more reliable than inline updates; see message queues and background jobs.
- Cost. Embedding a corpus is a one-time cost per content change; per-query embeddings are small but add up. OpenAI's Batch API documents a 50% discount for asynchronous jobs and lists the embeddings endpoint as supported, which suits bulk re-indexing.
- Observability. Log query, retrieved ids from each retriever, fused rank and latency per stage so you can see which retriever produced a result.
- Scaling. Start in Postgres; if vector latency or index size becomes the bottleneck, split retrieval into a dedicated service. Pooling and replicas are covered in scaling the backend.
- Security. Parameterise queries, enforce tenant filters in SQL, and rate-limit the search endpoint, since each request may trigger a paid embedding call.
Common mistakes
- Adding scores from different retrievers.
ts_rankand cosine distance are not comparable; fuse ranks, or normalise carefully. - Letting
to_tsquerytake raw user input. It raises errors on stray punctuation; usewebsearch_to_tsquery. - Filtering permissions after retrieval. This leaks data and returns too few results.
- No evaluation set. Without labels, every "improvement" is an opinion.
- Reranking everything. Rerank a small candidate set, or latency and cost balloon.
- Ignoring zero-result queries. They are the best source of synonyms, typos and content gaps.
- Embedding on the request path with no timeout. One slow API call stalls search; degrade gracefully to keyword results.
- Stale index. Content edits that do not update embeddings produce confident wrong results.
Best practices
- Start with keyword search as a baseline, add vectors, then measure the gain.
- Keep metadata (tenant, type, language, updated date) alongside every row and use it for filtering and boosting.
- Weight titles above body text for keyword search.
- Show users why a result matched with highlighted snippets.
- Review failed searches weekly and feed them back into your evaluation set.
- If an answer, not just links, is the goal, pass the top results into a RAG prompt with citations.
Conclusion
An AI-powered search system is mostly good retrieval engineering: two retrievers that fail in different ways, a merge step that does not depend on score scales, and an evaluation loop that tells you the truth. Postgres gives you all of the pieces in one place, and Node.js ties them together in a small amount of code.
Start by building the keyword baseline on your own content, add the vector retriever, and compute recall@10 for both on fifty real queries. If you want the generated-answer version of this system, continue with RAG architecture, or see my AI integration services for help building search into a product.
References
- PostgreSQL documentation: Full text search
- PostgreSQL documentation: Text search functions (websearch_to_tsquery, ts_rank_cd)
- pgvector on GitHub
- Reciprocal Rank Fusion outperforms Condorcet and individual rank learning methods (Cormack et al., SIGIR 2009)
- OpenAI: Embeddings guide
- OpenAI: Batch API guide
Written by Shivam Thakur, a Software Engineer focused on web applications, SaaS platforms and modern software products. More at shivamthakur.me.

