HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 28“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Semantic, Keyword and Hybrid Search
A learner on TechLearningPro pasted the support code PGV-2041 into the help assistant.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 28 · RAG, Search and Knowledge Systems
Lesson Overview
A learner on TechLearningPro pasted the support code PGV-2041 into the help assistant. The vector index had never been taught that string. The nearest neighbor was a paragraph about "model version," and the error-code article did not appear. The same week, a second learner asked "get my money back" and the keyword index missed the annual-plan article, because that article says "refunded" and "yearly" and never says "money." A third bug mixed a staff runbook into a learner result: the runbook also contains PGV-2041, and the ranker filtered the tenant only after it had already kept a global top five.
Keyword search ranks documents by the terms they share with the query. This lesson uses BM25, a term-frequency formula with a length penalty and a rarity weight. Semantic search ranks by cosine similarity on one embedder version, the rule from Embeddings, Similarity Search and Vector Fundamentals. Hybrid search keeps both ranked lists and fuses them with reciprocal rank fusion (RRF) so a rare identifier and a paraphrase can both survive. You will implement the three steps in TypeScript, on an in-memory corpus, with tenant, audience, and document version applied before either score exists.
The lexicon embedder is the same kind of teaching stand-in as lesson 17. It is a table of axes, not a neural model. BM25 here does not stem words and does not expand synonyms. refunded and refund are different terms on purpose. RRF uses rank position, not the raw BM25 number and not the cosine number. Those two numbers are different units. Averaging them is not a fusion method.
Planning assumptions:
The corpus is help text TechLearningPro already shows that audience, not another tenant's tickets and not a provider credential.
k1 = 1.2, b = 0.75, and RRF k = 60 are lab defaults. They are common published starting points, not a tuned relevance policy.
Semantic scores are comparable only for one embedderId and one dimension count.
No search vendor and no API key. PostgreSQL can store the same predicates later; this lesson keeps the rows in an array so the filters stay visible. The storage lesson is Vector Databases and PostgreSQL pgvector.
Learning Objectives
By the end of this lesson you will be able to:
State what BM25 rewards: a query term that is present, rarer in the corpus, and not diluted by a long document.
Compute a non-negative IDF and a saturated term-frequency term, and name k1 and b as lab constants.
Explain why a keyword index misses a paraphrase and why a vector index can miss a rare code.
Keep cosine as the semantic measure and refuse vectors whose embedder id or length disagrees.
Build both ranked lists only from rows that already match tenant, audience, and document version.
Fuse those lists with reciprocal rank fusion using 1-based ranks and a documented k.
Return a keyword hit when the semantic leg has no lexicon terms, and a semantic hit when BM25's terms never appear.
Leave staff-only rows out of a learner query even when they contain the same rare code.
Refuse to average a BM25 score with a cosine score.
Test the code path, the paraphrase path, the stale-version path, and the audience path without a network call.
Name what moves to SQL later: the same predicates, not a shared index that filters after top-k.
Point hybrid weights at an evaluation set instead of a single impressive query.
Lesson 17's cosine rule: same direction, same embedder, tenant filter first, empty neighbors are a normal outcome. This lesson does not redo the proof that scaling a vector leaves cosine unchanged.
Node.js 20 or newer for node:test. No embedding provider. The semantic leg calls embedLexicon.
Detailed Core Concepts
Two failure modes that do not share a score
Keyword search answers "which documents contain these terms?" Semantic search answers "which stored vectors point the same way as this query, under this embedder?" A help assistant needs both questions. The error code is the first question. "Get my money back" is the second, until someone writes the synonym down.
BM25 will not infer that money and refunded are related. The lexicon will not treat 2041 as a word it knows, so the semantic leg returns no vector for that query. Hybrid search is the policy that a miss on one leg is not a miss for the request. The HTTP handler still returns an empty list when both legs are empty. That empty list is what the later grounding lesson abstains on. It is not a cue to search another tenant.
BM25, in the units this lab uses
For a document D and a query term q that appears in D:
score(D) = sum over unique query terms of IDF(q) * tfSat(q, D)
N is the number of documents after the tenant, audience, and version filters. df(q) is how many of those documents contain q. |D| is the token count of D. avgdl is the mean token count of that same filtered set. A staff runbook must not change a learner's average length or a learner's document frequency.
The IDF form is the non-negative variant used by Lucene's BM25: the 1 + inside the log keeps a very common term from going negative. Classic Robertson IDF can be negative when a term appears in more than half the documents. This lab does not use that form. Say which form you ship. Mixing them between index time and query time changes order.
k1 controls how fast extra repetitions stop mattering. b controls how much a long document is discounted. 1.2 and 0.75 are the usual published defaults. On a three-document help corpus they are uncalibrated. Lesson 31 is where a change to them has to beat a stored baseline.
Worked behavior, not a universal ranking:
Query PGV-2041 tokenizes to pgv and 2041. Only the public error article contains both. Its score is positive. The refund article's score is 0 and is omitted from the keyword list.
Query get my money back shares money with the glossary and shares nothing with the annual-window article. Keyword search returns the glossary. That is a correct BM25 result and a bad answer. The semantic leg is what brings the window article back.
This tokenizer lowercases and splits on anything that is not a letter or digit. It does not stem, and it does not drop stop words. An undocumented stop list would change rank with no reviewable diff. If you add a list, store it next to k1 and b and add a test that names the dropped word.
Semantic leg
The lexicon has three axes, in order: refund, error, progress.
pgv and 2041 are absent. A query the table cannot place returns no_known_terms. The hybrid function treats that as an empty semantic list, not as an HTTP 500.
Cosine is the score. A row whose embedderId differs is not a candidate. A row whose vector is null because a backfill has not run is not a semantic candidate either. BM25 can still return that row. Shipping search only after every vector exists is how a re-embed job becomes an outage.
minSemanticScore defaults to 0.5 in the lab call site. It is a gate so orthogonal axes do not fill the list. It is not a claim that 0.5 means "relevant" on a trained model. A trained model replaces embedLexicon and keeps the id check.
Fusion by rank
Reciprocal rank fusion, as published by Cormack, Clarke, and Buettcher, scores a document by the ranks it earned:
text
RRF(d) = sum over lists that contain d of 1 / (k + rank_list(d))
Ranks start at 1. A document in one list still receives that list's term. With k = 60, rank 1 contributes 1/61 and rank 2 contributes 1/62. The top of each list matters, and a document that is rank 1 on both lists beats a document that is rank 1 on only one. The constant 60 flattens small rank gaps. It is the usual published constant, and it is still a lab default until you measure it.
RRF never reads the BM25 float or the cosine float. A cosine of 1 and a BM25 score of 1.8 are not "about the same." Weighted fusion, where you multiply each list by a hand-set weight, is a different product decision. This lab uses equal lists. Change a weight only when RAG Evaluation and Observability says the golden set moved.
Filters are not a score feature
Predicate
When it runs
What goes wrong if it runs late
tenantId from the session
Before BM25 statistics and before cosine
Another tenant's article changes df and can enter the top-k
audience
Same pass
A staff runbook that repeats PGV-2041 outranks the public article
documentVersion
Same pass
A retired "30 days" article competes with the current "14 days" article
embedderId
Semantic leg only
Two geometries land in one ranked list
The browser does not send the tenant id the server trusts, the embedder id, or a vector. A client-supplied tenant id that disagrees with the session is a 400, the same shape as lesson 17.
What hybrid search does not do
It does not call a generative model. It does not rerank with a cross-encoder. It does not prove the article answers the question. It returns ordered chunk ids the caller is allowed to read. Reranking is the next lesson. Citations are the lesson after that. If you skip ahead and paste the top hit into a prompt, you have not finished retrieval.
Architecture and Request Flow
flowchart TB
subgraph browser [Browser]
Box[Help query]
end
subgraph api [TechLearningPro API]
Auth[Session tenant and audience]
Hybrid[Hybrid search]
end
subgraph legs [Filtered corpus]
Kw[BM25 leg]
Sem[Cosine leg]
Fuse[Reciprocal rank fusion]
end
Box -->|GET q| Auth
Auth --> Hybrid
Hybrid --> Kw
Hybrid --> Sem
Kw --> Fuse
Sem --> Fuse
Fuse -->|chunk ids and ranks| Box
text
session tenant + audience + current document version
|
v
visible rows only
|
+--> tokenize query --> BM25 --> keyword rank list
|
+--> embedLexicon --> cosine, same embedder --> semantic rank list
|
v
RRF(k = 60) --> top limit hits
|
v
empty only when both lists are empty
flowchart LR
Q[Query text] --> Tok[Tokens]
Tok --> BM[BM25 on visible rows]
Tok --> Lex[Lexicon embedder]
Lex --> Cos[Cosine on matching embedder]
BM --> RRF[RRF]
Cos --> RRF
RRF --> Hits[Ordered chunk ids]
The browser receives ids, titles, and headings it may display. It does not receive vectors, BM25 internals, or rows that failed a predicate.
Step-by-step Implementation
Package path: packages/hybrid/. "strict": true. No network. No process.env.
Heading text is part of the BM25 document so a code in the heading is searchable. The semantic vector was computed from the chunk body at index time in this lab. Be explicit about that split when you index: if the heading carries the only copy of PGV-2041, the vector still will not know the code unless you embedded the heading too. Keyword search is the leg that saves you. Do not "fix" that by stuffing the code into a prompt synonym list and calling it semantic.
Step 5: Query path
Read the session. No session yields 401. tenantId and audience come from the session.
Read q. Trim. Empty or longer than 200 characters yields 400. A client tenantId that does not match the session yields 400.
Call hybridSearch with the catalog documentVersion you are serving, minSemanticScore: 0.5, perLegLimit: 20, limit: 5, and rrfK: 60.
On bad_vector, return 500 and a corrupt-index counter. A zero vector in a visible row is a bad backfill, not an empty search.
On success with zero hits, return 200, hits: [], and reason: "no_neighbor".
Return chunk id, title, heading, and the two ranks. Do not return vectors or the raw query to a shared analytics sink.
Nothing in the package reads the environment. Cleanup is deleting the package. A later adapter that calls an embedding API belongs behind the embedLexicon shape, with a timeout, and must not be required for this test file.
Security
Authentication runs before either leg. An anonymous help center, if you publish one, is a separate corpus of visibility: "learner" rows for a public tenant, not a mode that disables the filter.
Authorization is the audience predicate plus insert-time rules. A staff runbook is not inserted into the learner collection. The filter is defense in depth when a row is mis-tagged. Lesson 34 is the full permission model; this lesson still has to pass the audience test.
Least privilege for a future embedding credential: embed the query text, nothing else. The search process does not hold the role that writes billing.
Input validation caps q at 200 characters so the box cannot be used to push a document into an embedding bill.
Secrets do not belong in headings. The lab runbook sentence mentions provider keys only as a prohibition. The tests never contain a key.
Tenant isolation includes the statistics. IDF over the unfiltered corpus is a leak of "how many other tenants use this term" and a way for a foreign row to enter the rank list.
Retrieved text is untrusted data once a later lesson puts it in a prompt. This lesson's response is still product data: only rows the session may see. Responsible AI, Safety and Human-in-the-Loop Design is the policy layer. The predicate in visibleChunks is the control this lesson ships.
Error Handling
Case
Caller gets
Operator sees
Empty or oversized q
400 bad_query
Reject count, no query text
Both legs empty
200, hits: [], no_neighbor
Empty-search count
Semantic no_known_terms, keyword hit
200 with keyword-backed hits
legs.semantic = no_neighbor
Keyword miss, semantic hit
200 with semantic-backed hits
Keyword count 0
Eligible zero vector or dimension mismatch
500 bad_vector
Corrupt-index counter
rrfK outside 1..100
400 bad_query
Config error, not a user fault if the server set it
Future embedder timeout
200, keyword leg only, semantic: no_neighbor
Timeout metric, one try, no second model
Do not retry BM25. It is local and deterministic. Do not fall through to another tenant when the visible set is empty. Do not log q in a tool that staff from every tenant can read. A tenant-scoped trace may store the query under the same access rule as the conversation. The shared metric is a count.
Add a test that a chunk stored with embedderId: "other-model" does not appear on the semantic leg for get my money back. The row may still appear if BM25 matches. For the window article, drop yearly from a copy and you should see it vanish from the keyword leg and remain on the semantic leg. That is the regression you want locked before anyone averages the two scores in a follow-up patch.
Performance and Cost
This corpus is a linear scan. It is the right shape for the unit test and the wrong shape for every help article you have ever published. Lesson 27's index replaces the scan. It should keep visibleChunks as a mandatory predicate, ideally a partition or a WHERE the planner cannot skip. An approximate nearest-neighbor graph that searches every tenant and then drops rows has already loaded those vectors and has already biased the top-k.
Tokenize the query once and reuse it. The implementation above tokenizes inside BM25 and again inside embedLexicon. On this corpus that is noise. On a large corpus, pass the tokens in.
BM25 statistics are a pure function of the visible set. Cache them per (tenantId, audience, documentVersion) and invalidate on publish. Do not cache a fused result for one learner under another learner's key.
Embed the catalog at publish time. Search embeds the query only. A null vector means "keyword leg only for this row," not "embed the corpus inside the request."
Cap perLegLimit. RRF over thousands of ranks still costs the retrieval that produced them. Twenty per leg is the lab cap.
Do not log vectors or full article bodies at info level.
The cost surprise is a deploy that re-embeds every tenant because the model id was not pinned, or a fusion weight that doubles the candidate pool without a change in hit rate. Measure the pool in lesson 31 before you raise perLegLimit.
Knowledge Check
1. What problem does hybrid search solve?
It keeps a rare exact term and a paraphrase in one result list. BM25 returns PGV-2041 when the embedder has no axis for that code. Cosine returns the annual-window article for "get my money back" when those words are not in the article. RRF merges the two rank lists without adding a BM25 float to a cosine float.
2. What alternatives exist, and when would you choose each?
Keyword only, when the user is looking up a code, a slug, or a name they can spell. Semantic only, when you have one embedder version and the queries are paraphrases of text the embedder can place. Hybrid, when you have both query types in one box. A learned ranker or a weighted sum, only after a golden set says RRF is the wrong fusion. A vector database, when the linear scan is too slow, with the same filters.
3. Which data, identity, and trust boundaries matter?
The session owns tenantId and audience. documentVersion is the catalog you intend to serve, not a client hint that selects a retired policy. BM25's N, df, and avgdl are computed on the visible rows. The browser does not submit the vector. A future embedding API receives the query text, so the query must already be allowed to leave the trust zone.
4. What can fail, and how should the system respond?
An unknown lexicon query still returns keyword hits. A keyword miss still returns semantic hits. Both empty is 200 with no_neighbor. A corrupt vector on a visible row is bad_vector. A timeout on a future embedder degrades to the keyword leg and records the timeout. It does not scan a second embedder and it does not scan a second tenant.
5. How would you test quality, security, performance, and cost?
Unit tests lock the error code, the paraphrase, the staff runbook, the other tenant, and the stale version. Quality beyond the lexicon is a labeled set: hit rate at k for codes and for paraphrases, reported separately so one leg cannot hide the other. Security review checks that IDF cannot see staff rows on a learner request. Cost review checks publish-time embedding and a capped perLegLimit. A single screenshot of one query is not that review.
Hands-on Assignment
Lab note. Stay on embedLexicon and local BM25. Do not call a search vendor.
Problem. TechLearningPro help search should return chk_error for PGV-2041 to a learner, omit chk_runbook, and still return chk_window for "get my money back" even though BM25 did not rank that article.
Tasks.
Implement tokenize, bm25Rank, fuseRrf, and hybridSearch as specified.
Confirm by hand that PGV-2041 has no lexicon hit, then confirm the test returns one keyword rank and semantic: "no_neighbor".
Add the other-embedder test described above.
Write down k1, b, RRF k, and minSemanticScore as uncalibrated lab defaults. Name the lesson 31 evidence you would need to change each one.
Describe the SQL predicate you will not drop when this array becomes a table: tenant, audience, document version, then the two retrieval methods.
Deliverable. A diagram of the two legs, source with no secrets, test output, and the six-line note on constants.
Challenge. Add a second visible article that repeats money twenty times and show that BM25 does not let raw repetition swamp k1. Then state what you would refuse to do: multiply that BM25 score by cosine and sort.
Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and audience isolation 20%. Tests and failure behavior 20%. Documentation of fusion trade-offs 15%.
Common Mistakes
Averaging BM25 and cosine. Symptom: a perfect cosine loses to a long keyword soup, or the reverse, after a "simple" blend. Cause: two units were added. Fix: fuse ranks, or calibrate a real blend on a golden set.
Filtering after global top-k. Symptom: learners see a staff runbook, or a small tenant gets empty results. Cause: the index took five neighbors from everyone, then dropped some. Fix: visibleChunks before statistics and before cosine.
IDF on the unfiltered corpus. Symptom: scores shift when another tenant publishes. Cause: df counted rows the caller cannot see. Fix: compute N, df, and avgdl on the visible set only.
Stemming by surprise. Symptom: refund and refunded start matching and a test changes with no formula edit. Cause: a stemmer landed in the tokenizer. Fix: keep this lab unstemmed, or version the stemmer beside k1.
Treating the lexicon as a model. Symptom: a demo promises that any paraphrase will hit. Cause: the axis table was described as semantic understanding. Fix: call it a lexicon, and return no_neighbor when it misses.
One embedder id for two model versions. Symptom: ranks swing on deploy. Cause: vectors from different geometries share a list. Fix: store the id and skip mismatches.
Hiding keyword hits during a re-embed. Symptom: PGV-2041 disappears while vectors are null. Cause: search required a vector. Fix: a null vector skips the semantic leg for that row only.
Searching a stale document version. Symptom: the assistant quotes a 30-day refund. Cause: version was a boost instead of a filter. Fix: documentVersion is a predicate. Boosts are a later lesson.
Logging the query in a shared dashboard. Symptom: one tenant's support codes show up in another team's tool. Cause: debug logging was global. Fix: counts in shared metrics, raw text only in a tenant-scoped store.
Raising perLegLimit to fix one miss. Symptom: latency grows and the original miss remains, because the term was never in either index. Fix: inspect which leg should have recalled it, then change that leg or the content.
Summary
Hybrid search is two retrieval questions fused by rank. BM25 is for terms that are actually in the document, including codes the embedder has never seen. Cosine on one lexicon, and later one model version, is for paraphrases those axes can place. Reciprocal rank fusion keeps a hit from either list without pretending the raw scores share a unit. Tenant, audience, and document version decide which rows exist before either formula runs. An empty pair of lists is a normal miss. It is the handoff to reranking only when the lists are not empty, and to abstention when they are.
Next Lesson Preview
RAG Retrieval Optimization and Reranking starts from the fused list you just built. The glossary and the 14-day window can both be "about refunds." You will score query and chunk together, keep a token budget, and degrade to hybrid order when the reranker does not answer in time.
Lucene's BM25Similarity for the non-negative IDF this lesson implemented. Read the javadoc for the Lucene version you actually run before copying a constant into production.
Cormack, Clarke, and Buettcher, "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods" (SIGIR 2009), for the 1 / (k + rank) formula and the constant k = 60.
Ready to mark this lesson complete?Track your journey across the entire course.