{"id":319,"date":"2026-12-01T14:38:26","date_gmt":"2026-12-01T14:38:26","guid":{"rendered":"https:\/\/devdojo.co.in\/?p=319"},"modified":"2026-12-01T14:38:27","modified_gmt":"2026-12-01T14:38:27","slug":"genai-series-part-13-hybrid-search-reranking","status":"publish","type":"post","link":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/","title":{"rendered":"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting"},"content":{"rendered":"\n<div class=\"dd-post\">\n<style>\n.single article:has(.dd-hero) .entry-media{display:none}\n.dd-post{--navy:#0b1020;--blue:#3178c6;--violet:#7c5cff;--ink:#1f2433;--muted:#5b6275;--line:#e3e6ef;font-size:17px;line-height:1.75;color:var(--ink)}\n.dd-post h2{margin:2.2em 0 .6em;font-size:1.6em;line-height:1.3;scroll-margin-top:90px}\n.dd-post h3{margin:1.6em 0 .5em;font-size:1.22em;scroll-margin-top:90px}\n.dd-post a{color:var(--blue);text-decoration:underline;text-underline-offset:3px}\n.dd-post pre{background:#0f1430;color:#e6e9f5;padding:18px 20px;border-radius:12px;overflow-x:auto;line-height:1.6;border:1px solid #232a52;margin:1.2em 0;font-size:14.5px !important}\n.dd-post pre code{font-size:1em !important;background:none;color:inherit;padding:0;font-family:\"JetBrains Mono\",\"Fira Code\",Consolas,Menlo,monospace;white-space:pre}\n.dd-post :not(pre)>code{background:#eef1fb;color:#2b3a8f;padding:2px 6px;border-radius:5px;font-size:.9em}\n.dd-post .dd-file{display:inline-block;background:#151b3b;color:#c9d1ff;font:600 13px\/1 \"JetBrains Mono\",Consolas,monospace;padding:7px 12px;border-radius:8px 8px 0 0;margin:1em 0 -1.2em;position:relative}\n.dd-post .dd-hero{margin:0 0 1.6em;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(11,16,32,.25)}\n.dd-post .dd-hero svg{display:block;width:100%;height:auto}\n.dd-post .dd-hero .node{transition:transform .25s,filter .25s;transform-box:fill-box;transform-origin:center;cursor:pointer}\n.dd-post .dd-hero .node:hover{transform:scale(1.08);filter:drop-shadow(0 0 10px #7c5cff)}\n.dd-post .dd-series{display:inline-flex;align-items:center;gap:8px;background:#151b3b;color:#dfe3ff;border-radius:999px;padding:6px 14px;font-size:.88em;font-weight:600;margin:0 0 .8em}\n.dd-post .dd-series span{background:var(--violet);color:#fff;border-radius:999px;padding:2px 10px}\n.dd-post .dd-prereq{font-size:.96em;color:var(--muted);border-left:3px solid var(--line);padding-left:12px;margin:.6em 0 1.2em}\n.dd-post .dd-summary{background:linear-gradient(135deg,#eef3ff,#f4efff);border:1px solid #d6dcf5;border-left:5px solid var(--violet);border-radius:12px;padding:18px 22px;margin:1.4em 0}\n.dd-post .dd-summary strong.lbl{display:block;font-size:1.05em;margin-bottom:6px;color:#3a2fa0}\n.dd-post .dd-summary ul{margin:.3em 0 0 1.1em}\n.dd-post .dd-toc{background:#f8f9fc;border:1px solid var(--line);border-radius:12px;padding:16px 22px;margin:1.4em 0}\n.dd-post .dd-toc ol{margin:.4em 0 0 1.2em;columns:2;column-gap:28px}\n.dd-post .dd-toc li{break-inside:avoid;margin:.15em 0}\n@media(max-width:640px){.dd-post .dd-toc ol{columns:1}}\n.dd-post .dd-tip,.dd-post .dd-note,.dd-post .dd-warn{border-radius:10px;padding:14px 18px;margin:1.3em 0}\n.dd-post .dd-tip{background:#ecfbf3;border-left:4px solid #1f9d61}\n.dd-post .dd-note{background:#eef4ff;border-left:4px solid var(--blue)}\n.dd-post .dd-warn{background:#fff6e8;border-left:4px solid #e08a00}\n.dd-post .dd-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin:1.3em 0}\n.dd-post .dd-card{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:#fff;box-shadow:0 2px 8px rgba(20,30,70,.05)}\n.dd-post .dd-card b{display:block;color:#3a2fa0;margin-bottom:4px}\n.dd-post table{width:100%;border-collapse:collapse;margin:1.3em 0;font-size:.95em}\n.dd-post th,.dd-post td{border:1px solid var(--line);padding:10px 12px;text-align:left;vertical-align:top}\n.dd-post th{background:#151b3b;color:#fff}\n.dd-post tr:nth-child(even) td{background:#f8f9fc}\n.dd-post .dd-tablewrap{overflow-x:auto}\n.dd-post figure{margin:1.6em 0;text-align:center}\n.dd-post figure svg{width:100%;height:auto;border-radius:12px}\n.dd-post figcaption{font-size:.9em;color:var(--muted);margin-top:8px}\n.dd-post details{border:1px solid var(--line);border-radius:10px;padding:12px 16px;margin:.7em 0;background:#fff}\n.dd-post details summary{cursor:pointer;font-weight:600}\n.dd-post details[open] summary{margin-bottom:8px;color:#3a2fa0}\n.dd-post .dd-roadmap{border:2px solid #d6dcf5;background:#fbfbff}\n.dd-post .dd-roadmap h4{margin:1em 0 .3em;color:#151b3b;font-size:1em;text-transform:uppercase;letter-spacing:.04em}\n.dd-post .dd-roadmap ol{margin:.2em 0 .6em 1.4em;padding:0}\n.dd-post .dd-roadmap li{margin:.2em 0}\n.dd-post .dd-roadmap .here{background:var(--violet);color:#fff;border-radius:999px;padding:1px 9px;font-size:.8em;font-weight:700;margin-left:6px}\n.dd-post .dd-roadmap .soon{color:#8a90a6;font-size:.82em;margin-left:6px}\n.dd-post .dd-tabs{border:1px solid var(--line);border-radius:12px;padding:6px 16px 16px;margin:1.4em 0;background:#fbfbfe}\n.dd-post .dd-tabs>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-tabs .labels label{display:inline-block;padding:8px 16px;margin:10px 6px 0 0;border-radius:999px;border:1px solid #cfd5ea;cursor:pointer;font-weight:600;font-size:.95em;background:#fff;transition:background .2s}\n.dd-post .dd-tabs .labels label:hover{border-color:var(--violet)}\n.dd-post .dd-tabs .panel{display:none;margin-top:12px}\n.dd-post .dd-tabs #ti1:checked~.labels label[for=ti1],.dd-post .dd-tabs #ti2:checked~.labels label[for=ti2],.dd-post .dd-tabs #ti3:checked~.labels label[for=ti3],.dd-post .dd-tabs #ti4:checked~.labels label[for=ti4]{background:var(--violet);color:#fff;border-color:var(--violet)}\n.dd-post .dd-tabs #ti1:checked~.p1,.dd-post .dd-tabs #ti2:checked~.p2,.dd-post .dd-tabs #ti3:checked~.p3,.dd-post .dd-tabs #ti4:checked~.p4{display:block}\n.dd-post .dd-tabs #ti1:focus-visible~.labels label[for=ti1],.dd-post .dd-tabs #ti2:focus-visible~.labels label[for=ti2],.dd-post .dd-tabs #ti3:focus-visible~.labels label[for=ti3],.dd-post .dd-tabs #ti4:focus-visible~.labels label[for=ti4]{outline:2px solid var(--blue);outline-offset:2px}\n.dd-post .dd-cta{background:linear-gradient(135deg,#0b1020,#151b3b);color:#e8ebff;border-radius:16px;padding:24px 26px;margin:2em 0;text-align:center}\n.dd-post .dd-cta h3{color:#fff;margin-top:0}\n.dd-post .dd-cta a{color:#a99bff}\n.dd-post .dd-vsc{position:relative;margin:1.5em 0;border-radius:12px;overflow:hidden;background:#1e1e1e;border:1px solid #2b2b2b;box-shadow:0 14px 34px rgba(0,0,0,.28);font-family:\"Segoe UI\",system-ui,sans-serif}\n.dd-post .dd-vsc>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-vsc-bar{display:flex;align-items:center;gap:12px;background:#323233;color:#cccccc;font-size:12.5px;padding:8px 12px}\n.dd-post .dd-dots{display:inline-flex;gap:7px}.dd-post .dd-dots i{width:12px;height:12px;border-radius:50%;background:#ff5f57;display:block}.dd-post .dd-dots i:nth-child(2){background:#febc2e}.dd-post .dd-dots i:nth-child(3){background:#28c840}\n.dd-post .dd-vsc-title{flex:1;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:50px;opacity:.85}\n.dd-post .dd-vsc-tabs{display:flex;align-items:stretch;background:#252526;border-bottom:1px solid #1e1e1e;overflow-x:auto}\n.dd-post .dd-vsc-tabs label{display:flex;align-items:center;gap:7px;padding:9px 16px;color:#969696;font-size:13px;cursor:pointer;background:#2d2d2d;border-right:1px solid #252526;border-top:1px solid transparent;white-space:nowrap;margin:0;transition:color .15s}\n.dd-post .dd-vsc-tabs label:hover{color:#e0e0e0}\n.dd-post .dd-vsc-tabs .ic{font:700 9.5px\/1 Consolas,monospace;padding:3px 4px;border-radius:3px;color:#1e1e1e}\n.dd-post .ic.py{background:#ffd43b}.dd-post .ic.js{background:#f1e05a}.dd-post .ic.sh{background:#89e051}\n.dd-post .dd-vsc-tabs label.run{margin-left:auto;background:transparent;border:0;color:#89d185;font-weight:600;display:none}\n.dd-post .dd-vsc-tabs label.run:hover{color:#b5f0b0;background:#2a2d2e}\n.dd-post .dd-vsc-pane{display:none}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .t3{background:#1e1e1e;color:#ffffff;border-top-color:#3178c6}\n.dd-post .dd-vsc>.f1:checked~.p1,.dd-post .dd-vsc>.f2:checked~.p2,.dd-post .dd-vsc>.f3:checked~.p3{display:block}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .run1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .run2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .run3{display:flex}\n.dd-post .dd-vsc>.f1:focus-visible~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:focus-visible~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:focus-visible~.dd-vsc-tabs .t3,.dd-post .dd-vsc>input[type=checkbox]:focus-visible~.dd-vsc-tabs .run{outline:2px solid #3178c6;outline-offset:-2px}\n.dd-post .dd-vsc-crumbs{background:#1e1e1e;color:#a9a9a9;font-size:12px;padding:5px 16px 2px}\n.dd-post .dd-vsc pre.dd-vsc-code{background:#1e1e1e;color:#d4d4d4;border:0;border-radius:0;margin:0;padding:8px 0 14px;counter-reset:ln;line-height:1.62;overflow-x:auto}\n.dd-post .dd-vsc pre code{font-family:Consolas,\"JetBrains Mono\",\"Fira Code\",Menlo,monospace;color:inherit;background:none;white-space:pre}\n.dd-post .dd-vsc .l{display:inline-block;min-width:100%;padding-right:18px;box-sizing:border-box}\n.dd-post .dd-vsc .l::before{counter-increment:ln;content:counter(ln);display:inline-block;width:3.2em;padding-right:1.4em;text-align:right;color:#6e7681;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc .l:hover{background:#2a2d2e}.dd-post .dd-vsc .l:hover::before{color:#c6c6c6}\n.dd-post .dd-vsc .k,.dd-post .dd-vsc .kn{color:#c586c0}.dd-post .dd-vsc .kc{color:#569cd6}.dd-post .dd-vsc .s{color:#ce9178}.dd-post .dd-vsc .c{color:#6a9955}.dd-post .dd-vsc .m{color:#b5cea8}.dd-post .dd-vsc .nf{color:#dcdcaa}.dd-post .dd-vsc .nc{color:#4ec9b0}.dd-post .dd-vsc .nb{color:#4ec9b0}.dd-post .dd-vsc .nd{color:#dcdcaa}.dd-post .dd-vsc .n{color:#9cdcfe}.dd-post .dd-vsc .o{color:#d4d4d4}.dd-post .dd-vsc .gp{color:#89d185;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc-term{display:none;border-top:1px solid #3c3c3c;background:#181818}\n.dd-post .dd-vsc>.r1:checked~.p1 .dd-vsc-term,.dd-post .dd-vsc>.r2:checked~.p2 .dd-vsc-term,.dd-post .dd-vsc>.r3:checked~.p3 .dd-vsc-term{display:block;animation:ddterm .35s ease-out}\n@keyframes ddterm{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\n.dd-post .dd-term-head{display:flex;gap:18px;align-items:center;font-size:11px;letter-spacing:.06em;color:#8b8b8b;padding:7px 16px 0}\n.dd-post .dd-term-head span:first-child{color:#e7e7e7;border-bottom:1px solid #e7e7e7;padding-bottom:4px}\n.dd-post .dd-term-head .dd-term-note{margin-left:auto;letter-spacing:0;text-transform:none;color:#d7ba7d;border:0;font-size:11.5px}\n.dd-post .dd-vsc-term pre{background:#181818;color:#cccccc;border:0;margin:0;padding:10px 16px 14px;border-radius:0}\n.dd-post .dd-vsc-status{display:flex;flex-wrap:wrap;gap:4px 14px;background:#007acc;color:#fff;font-size:11.5px;padding:4px 12px}\n.dd-post .dd-vsc-status .sp{flex:1}\n.dd-post .dd-vsc-termonly pre.dd-vsc-code{background:#181818;padding:12px 16px}\n@media(max-width:640px){.dd-post .dd-vsc-title{padding-right:0;text-align:left}.dd-post .dd-vsc-status span:nth-child(n+4){display:none}.dd-post .dd-vsc .l::before{width:2.2em;padding-right:1em}}\n.dd-post .dd-vsc-hint{font-size:.93em;color:var(--muted);margin-top:-.6em}\n.dd-post .dd-next{border:1px dashed var(--violet);border-radius:12px;padding:16px 20px;margin:1.6em 0;background:#f7f4ff}\n<\/style>\n<style>.dd-post .ic.json{background:#cbcb41}<\/style>\n<div class=\"dd-hero\">\n<svg viewBox=\"0 0 1200 520\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Generative AI series Part 13 banner: a question is rewritten, searched with both keyword search and vector search, the two result lists are fused, a re-ranker reorders them and the top 3 chunks go to the LLM\">\n<defs>\n<linearGradient id=\"ddbg\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#0b1020\"\/><stop offset=\"1\" stop-color=\"#151b3b\"\/><\/linearGradient>\n<linearGradient id=\"ddac\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0\" stop-color=\"#3178c6\"\/><stop offset=\"1\" stop-color=\"#7c5cff\"\/><\/linearGradient>\n<radialGradient id=\"ddglow\" cx=\".5\" cy=\".5\" r=\".5\"><stop offset=\"0\" stop-color=\"#7c5cff\" stop-opacity=\".45\"\/><stop offset=\"1\" stop-color=\"#7c5cff\" stop-opacity=\"0\"\/><\/radialGradient>\n<\/defs>\n<rect x=\"0\" y=\"-60\" width=\"1200\" height=\"640\" fill=\"url(#ddbg)\"\/>\n<circle cx=\"1000\" cy=\"110\" r=\"250\" fill=\"url(#ddglow)\"\/>\n<g opacity=\".12\" stroke=\"#9fb2ff\"><path d=\"M0 100H1200M0 200H1200M0 300H1200M0 400H1200M200 0V520M400 0V520M600 0V520M800 0V520M1000 0V520\"\/><\/g>\n<rect x=\"60\" y=\"46\" width=\"140\" height=\"38\" rx=\"19\" fill=\"url(#ddac)\"\/>\n<text x=\"130\" y=\"71\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">PART 13<\/text>\n<text x=\"216\" y=\"71\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" fill=\"#aab4e8\">Generative AI Series \u00b7 DevDojo<\/text>\n<text x=\"60\" y=\"148\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"58\" font-weight=\"800\" fill=\"#ffffff\">Better RAG<\/text>\n<text x=\"60\" y=\"204\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"44\" font-weight=\"800\" fill=\"url(#ddac)\">Hybrid Search &amp; Re-ranking<\/text>\n<text x=\"60\" y=\"246\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"23\" fill=\"#c9d1ff\">Find the right chunk first: keyword + vector search, re-ranking, query rewriting<\/text>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<g class=\"node\"><rect x=\"40\" y=\"320\" width=\"170\" height=\"110\" rx=\"16\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"125\" y=\"352\" text-anchor=\"middle\" font-size=\"15\" fill=\"#aac8f0\">1 \u00b7 Rewrite<\/text><text x=\"125\" y=\"384\" text-anchor=\"middle\" font-size=\"16\" fill=\"#e8ebff\">&quot;money back<\/text><text x=\"125\" y=\"406\" text-anchor=\"middle\" font-size=\"16\" fill=\"#e8ebff\">for it?&quot;<\/text><\/g>\n<g class=\"node\"><rect x=\"290\" y=\"290\" width=\"200\" height=\"66\" rx=\"14\" fill=\"#0b1020\" stroke=\"#61dafb\" stroke-width=\"2\"\/><text x=\"390\" y=\"318\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#a8ecfb\">Keyword (BM25)<\/text><text x=\"390\" y=\"340\" text-anchor=\"middle\" font-size=\"13\" fill=\"#8f9ad0\">exact words, codes<\/text><\/g>\n<g class=\"node\"><rect x=\"290\" y=\"394\" width=\"200\" height=\"66\" rx=\"14\" fill=\"#0b1020\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"390\" y=\"422\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#c9bfff\">Vector search<\/text><text x=\"390\" y=\"444\" text-anchor=\"middle\" font-size=\"13\" fill=\"#8f9ad0\">meaning, synonyms<\/text><\/g>\n<g class=\"node\"><rect x=\"570\" y=\"330\" width=\"170\" height=\"90\" rx=\"20\" fill=\"url(#ddac)\"\/><text x=\"655\" y=\"365\" text-anchor=\"middle\" font-size=\"15\" fill=\"#dfe3ff\">2 \u00b7 Fuse<\/text><text x=\"655\" y=\"398\" text-anchor=\"middle\" font-size=\"26\" font-weight=\"800\" fill=\"#fff\">RRF<\/text><\/g>\n<g class=\"node\"><rect x=\"810\" y=\"330\" width=\"160\" height=\"90\" rx=\"16\" fill=\"#1b2250\" stroke=\"#e08a00\" stroke-width=\"2\"\/><text x=\"890\" y=\"365\" text-anchor=\"middle\" font-size=\"15\" fill=\"#ffd28a\">3 \u00b7 Re-rank<\/text><text x=\"890\" y=\"396\" text-anchor=\"middle\" font-size=\"15\" fill=\"#e8ebff\">cross-encoder<\/text><\/g>\n<g class=\"node\"><rect x=\"1030\" y=\"300\" width=\"140\" height=\"150\" rx=\"16\" fill=\"#1b2250\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"1100\" y=\"330\" text-anchor=\"middle\" font-size=\"15\" fill=\"#b8f0a0\">Top 3 \u2192 LLM<\/text>\n<rect x=\"1048\" y=\"346\" width=\"104\" height=\"24\" rx=\"7\" fill=\"#2a2160\" stroke=\"#7c5cff\"\/><text x=\"1100\" y=\"363\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">refund-1<\/text>\n<rect x=\"1048\" y=\"378\" width=\"104\" height=\"24\" rx=\"7\" fill=\"#1e2a5a\"\/><text x=\"1100\" y=\"395\" text-anchor=\"middle\" font-size=\"13\" fill=\"#c9d1ff\">refund-2<\/text>\n<rect x=\"1048\" y=\"410\" width=\"104\" height=\"24\" rx=\"7\" fill=\"#1e2a5a\"\/><text x=\"1100\" y=\"427\" text-anchor=\"middle\" font-size=\"13\" fill=\"#c9d1ff\">billing-1<\/text><\/g>\n<\/g>\n<path id=\"ddf1\" d=\"M210 375 L290 323\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf2\" d=\"M210 375 L290 427\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf3\" d=\"M490 323 L570 365\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf4\" d=\"M490 427 L570 385\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf5\" d=\"M740 375 L810 375\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf6\" d=\"M970 375 L1030 375\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<circle r=\"6\" fill=\"#61dafb\"><animateMotion dur=\"1.2s\" repeatCount=\"indefinite\"><mpath href=\"#ddf1\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#7c5cff\"><animateMotion dur=\"1.2s\" begin=\".2s\" repeatCount=\"indefinite\"><mpath href=\"#ddf2\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#61dafb\"><animateMotion dur=\"1.2s\" begin=\".4s\" repeatCount=\"indefinite\"><mpath href=\"#ddf3\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#7c5cff\"><animateMotion dur=\"1.2s\" begin=\".6s\" repeatCount=\"indefinite\"><mpath href=\"#ddf4\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#e08a00\"><animateMotion dur=\"1.2s\" begin=\".8s\" repeatCount=\"indefinite\"><mpath href=\"#ddf5\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#89e051\"><animateMotion dur=\"1.2s\" begin=\"1s\" repeatCount=\"indefinite\"><mpath href=\"#ddf6\"\/><\/animateMotion><\/circle>\n<text x=\"60\" y=\"505\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" fill=\"#7f89b5\">devdojo.co.in \u00b7 Beginner friendly \u00b7 Python + Node.js examples<\/text>\n<\/svg>\n<\/div>\n\n<div class=\"dd-series\">Series: Generative AI <span>Part 13 of 30<\/span><\/div>\n<p class=\"dd-prereq\"><strong>What you should know first:<\/strong> read <a href=\"https:\/\/devdojo.co.in\/?p=313\">Part 11: RAG Fundamentals<\/a> and <a href=\"https:\/\/devdojo.co.in\/?p=315\">Part 12: Document Loading and Chunking<\/a>. You need Python 3.10+ or Node.js 20+. The keyword search and fusion examples need no API key and no downloads.<\/p>\n\n<p>In Part 12 our test showed something worrying: sometimes the retriever picks the wrong chunk, and then even the best LLM gives a wrong answer. In this post you will fix that with three upgrades that real RAG systems use every day. <strong>Hybrid search<\/strong> runs keyword search (BM25) and vector search together and merges the results, so you catch both exact words like error codes and similar meanings like &#8220;money back&#8221; = &#8220;refund&#8221;. <strong>Re-ranking<\/strong> uses a second, more careful model to put the best chunk on top. <strong>Query rewriting<\/strong> turns vague or follow-up questions into clear search queries. You will build each one in Python and Node.js, step by step.<\/p>\n\n<div class=\"dd-summary\">\n<strong class=\"lbl\">Quick Summary<\/strong>\n<ul>\n<li><strong>Vector search<\/strong> understands meaning but can miss exact words (error codes, product names). <strong>Keyword search (BM25)<\/strong> finds exact words but misses synonyms.<\/li>\n<li><strong>Hybrid search<\/strong> runs both and merges the two ranked lists, usually with <strong>Reciprocal Rank Fusion (RRF)<\/strong>: score = sum of 1 \/ (60 + rank).<\/li>\n<li><strong>Re-ranking<\/strong>: take the top 20&#8211;50 results and let a <strong>cross-encoder<\/strong> score each (question, chunk) pair. Slower, but much more accurate.<\/li>\n<li><strong>Query rewriting<\/strong>: let an LLM turn &#8220;what about it?&#8221; into a full question, create several search queries (multi-query) or write a fake answer to search with (HyDE).<\/li>\n<li>Good order: rewrite &#8594; hybrid search (wide) &#8594; re-rank (narrow) &#8594; send the top 3&#8211;5 chunks to the LLM. Measure each step with your test questions.<\/li>\n<\/ul>\n<\/div>\n\n<nav class=\"dd-toc\" aria-label=\"Table of contents\">\n<strong>In this post<\/strong>\n<ol>\n<li><a href=\"#why\">Why basic RAG retrieval misses<\/a><\/li>\n<li><a href=\"#bm25\">Keyword search with BM25<\/a><\/li>\n<li><a href=\"#hybrid-search\">Hybrid search with RRF<\/a><\/li>\n<li><a href=\"#rerank\">Re-ranking with a cross-encoder<\/a><\/li>\n<li><a href=\"#rewrite\">Query rewriting<\/a><\/li>\n<li><a href=\"#which\">Which fix solves which problem?<\/a><\/li>\n<li><a href=\"#pipeline\">The full retrieval pipeline<\/a><\/li>\n<li><a href=\"#databases\">Hybrid search in vector databases<\/a><\/li>\n<li><a href=\"#errors\">Common errors and fixes<\/a><\/li>\n<li><a href=\"#best\">Best practices<\/a><\/li>\n<li><a href=\"#practice\">Practice task<\/a><\/li>\n<li><a href=\"#faq\">FAQ<\/a><\/li>\n<\/ol>\n<\/nav>\n\n<details class=\"dd-roadmap\">\n<summary>Full Generative AI roadmap (30 parts)<\/summary>\n<h4>Beginner<\/h4>\n<ol start=\"1\">\n<li><a href=\"https:\/\/devdojo.co.in\/?p=215\">What Is Generative AI and How Do LLMs Work?<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=219\">Tokens, Context Windows and Model Parameters<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=223\">Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=240\">Prompt Engineering Basics: Roles, Instructions and Examples<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=244\">Temperature, Top-p and Controlling Model Output<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=281\">Run LLMs Locally with Ollama<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=284\">Streaming Responses and Building a Simple Chat UI<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=303\">Structured Outputs: Getting Reliable JSON from LLMs<\/a><\/li>\n<\/ol>\n<h4>Intermediate<\/h4>\n<ol start=\"9\">\n<li><a href=\"https:\/\/devdojo.co.in\/?p=306\">Embeddings Explained: Turning Text into Vectors<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=310\">Vector Databases: pgvector, Chroma and Pinecone<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=313\">RAG Fundamentals: Retrieval-Augmented Generation<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=315\">Document Loading and Chunking Strategies<\/a><\/li>\n<li><strong>Better RAG: Hybrid Search, Re-ranking and Query Rewriting<\/strong><span class=\"here\">You are here<\/span><\/li>\n<li>Function Calling and Tool Use<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Conversation Memory and Long Context Management<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Multimodal AI: Vision, Images and Audio Inputs<span class=\"soon\">Coming soon<\/span><\/li>\n<li>How Image Generation Works: Diffusion Models Basics<span class=\"soon\">Coming soon<\/span><\/li>\n<li>LangChain vs LlamaIndex: When to Use a Framework<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Testing LLM Apps: Evals, Metrics and Test Sets<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Cutting Cost and Latency: Caching, Batching and Model Choice<span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<h4>Advanced<\/h4>\n<ol start=\"21\">\n<li>Fine-Tuning vs Prompting vs RAG: Choosing the Right Tool<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Fine-Tuning an Open Model with LoRA<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Transformers Deep Dive: Attention Explained Simply<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Reasoning Models and Thinking Time<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Guardrails, Safety and Prompt Injection Defence<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Monitoring and Tracing LLM Apps in Production<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Serving Open Models: vLLM, Quantization and GPUs<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Building a Production GenAI App End to End<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Responsible AI: Privacy, Licensing and Bias<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Final Project: Build Your Own AI Knowledge Assistant<span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<\/details>\n\n<h2 id=\"why\">Why basic RAG retrieval misses<\/h2>\n<p>The RAG app from <a href=\"https:\/\/devdojo.co.in\/?p=313\">Part 11<\/a> used only <strong>vector search<\/strong>: turn the question into an embedding and return the chunks whose embeddings are closest. That works well for questions phrased in normal language. But it has blind spots:<\/p>\n<ul>\n<li><strong>Exact words get blurred.<\/strong> An embedding stores the <em>meaning<\/em> of a text, not its exact letters. &#8220;Error E-1042&#8221; and &#8220;Error E-1024&#8221; look almost the same to an embedding model, but they are two different problems for your users.<\/li>\n<li><strong>Rare names and new terms.<\/strong> Product names, function names, invoice numbers or internal team words may not mean anything to the embedding model.<\/li>\n<li><strong>Vague questions.<\/strong> &#8220;Can I still do that?&#8221; has no useful meaning on its own. The real question is hidden in the chat history.<\/li>\n<li><strong>Close-but-wrong chunks.<\/strong> The top result is often <em>about<\/em> the right topic but does not contain the answer, while the chunk with the answer sits at position 6.<\/li>\n<\/ul>\n<p>Keyword search has the opposite problem: it finds exact words perfectly, but a user who writes &#8220;money back&#8221; will not match a chunk that only says &#8220;refund&#8221;. The good news: these two methods fail in <em>different<\/em> places, so combining them works much better than either one alone.<\/p>\n\n<figure>\n<svg viewBox=\"0 0 900 330\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Comparison: keyword search finds error code E-1042 but misses money back versus refund; vector search finds refund for money back but can blur exact codes; hybrid search finds both\">\n<rect width=\"900\" height=\"330\" rx=\"14\" fill=\"#0f1430\"\/>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<text x=\"450\" y=\"40\" text-anchor=\"middle\" font-size=\"20\" font-weight=\"700\" fill=\"#fff\">Two searches, two different blind spots<\/text>\n<rect x=\"30\" y=\"66\" width=\"260\" height=\"230\" rx=\"14\" fill=\"#151b3b\" stroke=\"#61dafb\" stroke-width=\"2\"\/>\n<text x=\"160\" y=\"98\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"700\" fill=\"#a8ecfb\">Keyword (BM25)<\/text>\n<text x=\"50\" y=\"140\" font-size=\"15\" fill=\"#e8ebff\">&quot;error E-1042&quot;<\/text><text x=\"270\" y=\"140\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#89e051\">found<\/text>\n<text x=\"50\" y=\"176\" font-size=\"15\" fill=\"#e8ebff\">&quot;money back?&quot;<\/text><text x=\"270\" y=\"176\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#ff7b72\">half<\/text>\n<text x=\"50\" y=\"226\" font-size=\"13\" fill=\"#8f9ad0\">Matches exact words.<\/text><text x=\"50\" y=\"248\" font-size=\"13\" fill=\"#8f9ad0\">Does not know &quot;refund&quot;<\/text><text x=\"50\" y=\"270\" font-size=\"13\" fill=\"#8f9ad0\">means &quot;money back&quot;.<\/text>\n<rect x=\"320\" y=\"66\" width=\"260\" height=\"230\" rx=\"14\" fill=\"#151b3b\" stroke=\"#7c5cff\" stroke-width=\"2\"\/>\n<text x=\"450\" y=\"98\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"700\" fill=\"#c9bfff\">Vector search<\/text>\n<text x=\"340\" y=\"140\" font-size=\"15\" fill=\"#e8ebff\">&quot;error E-1042&quot;<\/text><text x=\"560\" y=\"140\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#e08a00\">risky<\/text>\n<text x=\"340\" y=\"176\" font-size=\"15\" fill=\"#e8ebff\">&quot;money back?&quot;<\/text><text x=\"560\" y=\"176\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#89e051\">found<\/text>\n<text x=\"340\" y=\"226\" font-size=\"13\" fill=\"#8f9ad0\">Matches meaning.<\/text><text x=\"340\" y=\"248\" font-size=\"13\" fill=\"#8f9ad0\">Codes, IDs and rare names<\/text><text x=\"340\" y=\"270\" font-size=\"13\" fill=\"#8f9ad0\">can get blurred.<\/text>\n<rect x=\"610\" y=\"66\" width=\"260\" height=\"230\" rx=\"14\" fill=\"url(#f1ac)\"\/>\n<defs><linearGradient id=\"f1ac\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#3178c6\"\/><stop offset=\"1\" stop-color=\"#7c5cff\"\/><\/linearGradient><\/defs>\n<text x=\"740\" y=\"98\" text-anchor=\"middle\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">Hybrid search<\/text>\n<text x=\"630\" y=\"140\" font-size=\"15\" fill=\"#fff\">&quot;error E-1042&quot;<\/text><text x=\"850\" y=\"140\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#d8ffcc\">found<\/text>\n<text x=\"630\" y=\"176\" font-size=\"15\" fill=\"#fff\">&quot;money back?&quot;<\/text><text x=\"850\" y=\"176\" text-anchor=\"end\" font-size=\"15\" font-weight=\"700\" fill=\"#d8ffcc\">found<\/text>\n<text x=\"630\" y=\"226\" font-size=\"13\" fill=\"#e8ebff\">Runs both searches and<\/text><text x=\"630\" y=\"248\" font-size=\"13\" fill=\"#e8ebff\">merges the ranked lists,<\/text><text x=\"630\" y=\"270\" font-size=\"13\" fill=\"#e8ebff\">so each covers the other.<\/text>\n<\/g>\n<\/svg>\n<figcaption>Keyword search and vector search fail in different places. Hybrid search combines them.<\/figcaption>\n<\/figure>\n\n<h2 id=\"bm25\">Keyword search with BM25<\/h2>\n<p><strong>BM25<\/strong> (&#8220;Best Matching 25&#8221;) is the classic keyword ranking formula used by search engines like Elasticsearch, OpenSearch and Lucene. You do not need to memorise the maths. It follows three simple ideas:<\/p>\n<div class=\"dd-cards\">\n<div class=\"dd-card\"><b>1. Rare words count more<\/b>&#8220;E-1042&#8221; appears in one chunk, so it is a strong signal. &#8220;plan&#8221; appears everywhere, so it is weak. This is called IDF (inverse document frequency).<\/div>\n<div class=\"dd-card\"><b>2. Repeats help, but less each time<\/b>A word that appears 3 times scores higher than once, but not 3&#215; higher. The <code>k1<\/code> setting controls this.<\/div>\n<div class=\"dd-card\"><b>3. Short chunks get a boost<\/b>A match in a 10-word chunk is more focused than the same match in a 500-word chunk. The <code>b<\/code> setting controls this.<\/div>\n<\/div>\n<p>We will use the same small help-centre knowledge base for every example in this post. Save it as <code>docs.json<\/code>:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: docs.json\">\n<input type=\"radio\" name=\"v0\" id=\"v0f1\" class=\"f1\" checked>\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">docs.json \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v0f1\" class=\"t1\"><b class=\"ic json\">{ }<\/b>docs.json<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a docs.json<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\">[<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"refund-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"Refund policy: you can ask for a full refund within 14 days of buying DevDojo Pro.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"refund-2\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"After 14 days money back is not possible, but you can pause your plan for one month.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"billing-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"To cancel your subscription, open Settings, then Billing, and click Cancel plan.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"pay-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"Error E-1042 means the bank declined your payment card. Try another card or pay with UPI.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"pay-2\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"We accept UPI, credit cards, debit cards and net banking for all payments.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"mentor-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"Mentors review your project and reply within 48 hours on weekdays.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"cert-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"You get a certificate after you finish all lessons and the final project.\"<\/span>},<\/span>\n<span class=\"l\"> {<span class=\"n\">\"id\"<\/span>: <span class=\"s\">\"support-1\"<\/span>, <span class=\"n\">\"text\"<\/span>: <span class=\"s\">\"Support chat is open from 10 AM to 7 PM IST, Monday to Saturday.\"<\/span>}<\/span>\n<span class=\"l\">]<\/span><\/code><\/pre>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 10, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>JSON<\/span><\/div>\n<\/div>\n<\/div>\n<p>Now a complete BM25 search in about 30 lines, with no libraries. Click the tabs to switch between Python and Node.js, and click <strong>\u25b6 Run<\/strong> to see the real output:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: bm25_search.py, bm25_search.mjs\">\n<input type=\"radio\" name=\"v1\" id=\"v1f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v1\" id=\"v1f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v1r1\" class=\"r1\">\n<input type=\"checkbox\" id=\"v1r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">bm25_search.py \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v1f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>bm25_search.py<\/label>\n<label for=\"v1f2\" class=\"t2\"><b class=\"ic js\">JS<\/b>bm25_search.mjs<\/label>\n<label for=\"v1r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<label for=\"v1r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a bm25_search.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span>, <span class=\"n\">math<\/span>, <span class=\"n\">re<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">collections<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Counter<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">STOP<\/span> = {<span class=\"s\">\"a\"<\/span>, <span class=\"s\">\"an\"<\/span>, <span class=\"s\">\"the\"<\/span>, <span class=\"s\">\"is\"<\/span>, <span class=\"s\">\"are\"<\/span>, <span class=\"s\">\"to\"<\/span>, <span class=\"s\">\"of\"<\/span>, <span class=\"s\">\"and\"<\/span>, <span class=\"s\">\"or\"<\/span>, <span class=\"s\">\"for\"<\/span>, <span class=\"s\">\"you\"<\/span>, <span class=\"s\">\"your\"<\/span>, <span class=\"s\">\"my\"<\/span>, <span class=\"s\">\"i\"<\/span>, <span class=\"s\">\"can\"<\/span>, <span class=\"s\">\"how\"<\/span>, <span class=\"s\">\"do\"<\/span>, <span class=\"s\">\"what\"<\/span>, <span class=\"s\">\"with\"<\/span>, <span class=\"s\">\"on\"<\/span>, <span class=\"s\">\"in\"<\/span>, <span class=\"s\">\"after\"<\/span>, <span class=\"s\">\"all\"<\/span>, <span class=\"s\">\"get\"<\/span>}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">tokenize<\/span>(<span class=\"n\">text<\/span>):<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">w<\/span> <span class=\"k\">for<\/span> <span class=\"n\">w<\/span> <span class=\"k\">in<\/span> <span class=\"n\">re<\/span>.<span class=\"n\">findall<\/span>(<span class=\"s\">r\"[a-z0-9]+(?:-[a-z0-9]+)*\"<\/span>, <span class=\"n\">text<\/span>.<span class=\"n\">lower<\/span>()) <span class=\"k\">if<\/span> <span class=\"n\">w<\/span> <span class=\"k\">not<\/span> <span class=\"k\">in<\/span> <span class=\"n\">STOP<\/span>]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">BM25<\/span>:<\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">__init__<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">docs<\/span>, <span class=\"n\">k1<\/span>=<span class=\"m\">1.5<\/span>, <span class=\"n\">b<\/span>=<span class=\"m\">0.75<\/span>):<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">docs<\/span> = <span class=\"n\">docs<\/span><\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span> = [<span class=\"n\">tokenize<\/span>(<span class=\"n\">d<\/span>[<span class=\"s\">\"text\"<\/span>]) <span class=\"k\">for<\/span> <span class=\"n\">d<\/span> <span class=\"k\">in<\/span> <span class=\"n\">docs<\/span>]<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">avg_len<\/span> = <span class=\"nb\">sum<\/span>(<span class=\"nb\">len<\/span>(<span class=\"n\">t<\/span>) <span class=\"k\">for<\/span> <span class=\"n\">t<\/span> <span class=\"k\">in<\/span> <span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span>) \/ <span class=\"nb\">len<\/span>(<span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span>)<\/span>\n<span class=\"l\">        <span class=\"n\">df<\/span> = <span class=\"n\">Counter<\/span>(<span class=\"n\">w<\/span> <span class=\"k\">for<\/span> <span class=\"n\">t<\/span> <span class=\"k\">in<\/span> <span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span> <span class=\"k\">for<\/span> <span class=\"n\">w<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">set<\/span>(<span class=\"n\">t<\/span>))<\/span>\n<span class=\"l\">        <span class=\"n\">n<\/span> = <span class=\"nb\">len<\/span>(<span class=\"n\">docs<\/span>)<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">idf<\/span> = {<span class=\"n\">w<\/span>: <span class=\"n\">math<\/span>.<span class=\"n\">log<\/span>(<span class=\"m\">1<\/span> + (<span class=\"n\">n<\/span> - <span class=\"n\">f<\/span> + <span class=\"m\">0.5<\/span>) \/ (<span class=\"n\">f<\/span> + <span class=\"m\">0.5<\/span>)) <span class=\"k\">for<\/span> <span class=\"n\">w<\/span>, <span class=\"n\">f<\/span> <span class=\"k\">in<\/span> <span class=\"n\">df<\/span>.<span class=\"n\">items<\/span>()}<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">k1<\/span>, <span class=\"kc\">self<\/span>.<span class=\"n\">b<\/span> = <span class=\"n\">k1<\/span>, <span class=\"n\">b<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">score<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">query<\/span>, <span class=\"n\">i<\/span>):<\/span>\n<span class=\"l\">        <span class=\"n\">tf<\/span>, <span class=\"n\">dl<\/span> = <span class=\"n\">Counter<\/span>(<span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span>[<span class=\"n\">i<\/span>]), <span class=\"nb\">len<\/span>(<span class=\"kc\">self<\/span>.<span class=\"n\">toks<\/span>[<span class=\"n\">i<\/span>])<\/span>\n<span class=\"l\">        <span class=\"n\">s<\/span> = <span class=\"m\">0.0<\/span><\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">w<\/span> <span class=\"k\">in<\/span> <span class=\"n\">tokenize<\/span>(<span class=\"n\">query<\/span>):<\/span>\n<span class=\"l\">            <span class=\"k\">if<\/span> <span class=\"n\">w<\/span> <span class=\"k\">in<\/span> <span class=\"n\">tf<\/span>:<\/span>\n<span class=\"l\">                <span class=\"n\">f<\/span> = <span class=\"n\">tf<\/span>[<span class=\"n\">w<\/span>]<\/span>\n<span class=\"l\">                <span class=\"n\">s<\/span> += <span class=\"kc\">self<\/span>.<span class=\"n\">idf<\/span>[<span class=\"n\">w<\/span>] * <span class=\"n\">f<\/span> * (<span class=\"kc\">self<\/span>.<span class=\"n\">k1<\/span> + <span class=\"m\">1<\/span>) \/ (<span class=\"n\">f<\/span> + <span class=\"kc\">self<\/span>.<span class=\"n\">k1<\/span> * (<span class=\"m\">1<\/span> - <span class=\"kc\">self<\/span>.<span class=\"n\">b<\/span> + <span class=\"kc\">self<\/span>.<span class=\"n\">b<\/span> * <span class=\"n\">dl<\/span> \/ <span class=\"kc\">self<\/span>.<span class=\"n\">avg_len<\/span>))<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> <span class=\"n\">s<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">search<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">query<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">3<\/span>):<\/span>\n<span class=\"l\">        <span class=\"n\">scored<\/span> = [(<span class=\"kc\">self<\/span>.<span class=\"n\">score<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">i<\/span>), <span class=\"n\">d<\/span>[<span class=\"s\">\"id\"<\/span>]) <span class=\"k\">for<\/span> <span class=\"n\">i<\/span>, <span class=\"n\">d<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">enumerate<\/span>(<span class=\"kc\">self<\/span>.<span class=\"n\">docs<\/span>)]<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> [(<span class=\"n\">doc_id<\/span>, <span class=\"nb\">round<\/span>(<span class=\"n\">s<\/span>, <span class=\"m\">2<\/span>)) <span class=\"k\">for<\/span> <span class=\"n\">s<\/span>, <span class=\"n\">doc_id<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">sorted<\/span>(<span class=\"n\">scored<\/span>, <span class=\"n\">reverse<\/span>=<span class=\"kc\">True<\/span>)[:<span class=\"n\">k<\/span>] <span class=\"k\">if<\/span> <span class=\"n\">s<\/span> &gt; <span class=\"m\">0<\/span>]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">if<\/span> <span class=\"n\">__name__<\/span> == <span class=\"s\">\"__main__\"<\/span>:<\/span>\n<span class=\"l\">    <span class=\"n\">docs<\/span> = <span class=\"n\">json<\/span>.<span class=\"n\">load<\/span>(<span class=\"nb\">open<\/span>(<span class=\"s\">\"docs.json\"<\/span>))<\/span>\n<span class=\"l\">    <span class=\"n\">bm25<\/span> = <span class=\"n\">BM25<\/span>(<span class=\"n\">docs<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">q<\/span> <span class=\"k\">in<\/span> [<span class=\"s\">\"error E-1042\"<\/span>, <span class=\"s\">\"can I get my money back?\"<\/span>, <span class=\"s\">\"how do I get a refund\"<\/span>]:<\/span>\n<span class=\"l\">        <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">q<\/span><span class=\"s\">!r:28} -&gt; {<\/span><span class=\"n\">bm25<\/span>.<span class=\"n\">search<\/span>(<span class=\"n\">q<\/span>)<span class=\"s\">}\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python bm25_search.py\n&#x27;error E-1042&#x27;               -&gt; [(&#x27;pay-1&#x27;, 3.23)]\n&#x27;can I get my money back?&#x27;   -&gt; [(&#x27;refund-2&#x27;, 3.37)]\n&#x27;how do I get a refund&#x27;      -&gt; [(&#x27;refund-1&#x27;, 2.45)]<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 36, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a bm25_search.mjs<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">readFileSync<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"node:fs\"<\/span>;<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">STOP<\/span> = <span class=\"k\">new<\/span> <span class=\"nb\">Set<\/span>([<span class=\"s\">\"a\"<\/span>, <span class=\"s\">\"an\"<\/span>, <span class=\"s\">\"the\"<\/span>, <span class=\"s\">\"is\"<\/span>, <span class=\"s\">\"are\"<\/span>, <span class=\"s\">\"to\"<\/span>, <span class=\"s\">\"of\"<\/span>, <span class=\"s\">\"and\"<\/span>, <span class=\"s\">\"or\"<\/span>, <span class=\"s\">\"for\"<\/span>, <span class=\"s\">\"you\"<\/span>, <span class=\"s\">\"your\"<\/span>, <span class=\"s\">\"my\"<\/span>, <span class=\"s\">\"i\"<\/span>, <span class=\"s\">\"can\"<\/span>, <span class=\"s\">\"how\"<\/span>, <span class=\"s\">\"do\"<\/span>, <span class=\"s\">\"what\"<\/span>, <span class=\"s\">\"with\"<\/span>, <span class=\"s\">\"on\"<\/span>, <span class=\"s\">\"in\"<\/span>, <span class=\"s\">\"after\"<\/span>, <span class=\"s\">\"all\"<\/span>, <span class=\"s\">\"get\"<\/span>]);<\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">tokenize<\/span> = (<span class=\"n\">text<\/span>) =&gt;<\/span>\n<span class=\"l\">  (<span class=\"n\">text<\/span>.<span class=\"n\">toLowerCase<\/span>().<span class=\"n\">match<\/span>(<span class=\"s\">\/[a-z0-9]+(?:-[a-z0-9]+)*\/g<\/span>) ?? []).<span class=\"n\">filter<\/span>((<span class=\"n\">w<\/span>) =&gt; !<span class=\"n\">STOP<\/span>.<span class=\"n\">has<\/span>(<span class=\"n\">w<\/span>));<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">function<\/span> <span class=\"n\">buildBM25<\/span>(<span class=\"n\">docs<\/span>, <span class=\"n\">k1<\/span> = <span class=\"m\">1.5<\/span>, <span class=\"n\">b<\/span> = <span class=\"m\">0.75<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"k\">const<\/span> <span class=\"n\">toks<\/span> = <span class=\"n\">docs<\/span>.<span class=\"n\">map<\/span>((<span class=\"n\">d<\/span>) =&gt; <span class=\"n\">tokenize<\/span>(<span class=\"n\">d<\/span>.<span class=\"n\">text<\/span>));<\/span>\n<span class=\"l\">  <span class=\"k\">const<\/span> <span class=\"n\">avgLen<\/span> = <span class=\"n\">toks<\/span>.<span class=\"n\">reduce<\/span>((<span class=\"n\">sum<\/span>, <span class=\"n\">t<\/span>) =&gt; <span class=\"n\">sum<\/span> + <span class=\"n\">t<\/span>.<span class=\"n\">length<\/span>, <span class=\"m\">0<\/span>) \/ <span class=\"n\">toks<\/span>.<span class=\"n\">length<\/span>;<\/span>\n<span class=\"l\">  <span class=\"k\">const<\/span> <span class=\"n\">df<\/span> = <span class=\"k\">new<\/span> <span class=\"nb\">Map<\/span>();<\/span>\n<span class=\"l\">  <span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">t<\/span> <span class=\"k\">of<\/span> <span class=\"n\">toks<\/span>) <span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">w<\/span> <span class=\"k\">of<\/span> <span class=\"k\">new<\/span> <span class=\"nb\">Set<\/span>(<span class=\"n\">t<\/span>)) <span class=\"n\">df<\/span>.<span class=\"n\">set<\/span>(<span class=\"n\">w<\/span>, (<span class=\"n\">df<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">w<\/span>) ?? <span class=\"m\">0<\/span>) + <span class=\"m\">1<\/span>);<\/span>\n<span class=\"l\">  <span class=\"k\">const<\/span> <span class=\"n\">idf<\/span> = (<span class=\"n\">w<\/span>) =&gt; <span class=\"nb\">Math<\/span>.<span class=\"n\">log<\/span>(<span class=\"m\">1<\/span> + (<span class=\"n\">docs<\/span>.<span class=\"n\">length<\/span> - <span class=\"n\">df<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">w<\/span>) + <span class=\"m\">0.5<\/span>) \/ (<span class=\"n\">df<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">w<\/span>) + <span class=\"m\">0.5<\/span>));<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> <span class=\"k\">function<\/span> <span class=\"n\">search<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">k<\/span> = <span class=\"m\">3<\/span>) {<\/span>\n<span class=\"l\">    <span class=\"k\">const<\/span> <span class=\"n\">results<\/span> = <span class=\"n\">docs<\/span>.<span class=\"n\">map<\/span>((<span class=\"n\">d<\/span>, <span class=\"n\">i<\/span>) =&gt; {<\/span>\n<span class=\"l\">      <span class=\"k\">const<\/span> <span class=\"n\">counts<\/span> = <span class=\"k\">new<\/span> <span class=\"nb\">Map<\/span>();<\/span>\n<span class=\"l\">      <span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">w<\/span> <span class=\"k\">of<\/span> <span class=\"n\">toks<\/span>[<span class=\"n\">i<\/span>]) <span class=\"n\">counts<\/span>.<span class=\"n\">set<\/span>(<span class=\"n\">w<\/span>, (<span class=\"n\">counts<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">w<\/span>) ?? <span class=\"m\">0<\/span>) + <span class=\"m\">1<\/span>);<\/span>\n<span class=\"l\">      <span class=\"k\">let<\/span> <span class=\"n\">score<\/span> = <span class=\"m\">0<\/span>;<\/span>\n<span class=\"l\">      <span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">w<\/span> <span class=\"k\">of<\/span> <span class=\"n\">tokenize<\/span>(<span class=\"n\">query<\/span>)) {<\/span>\n<span class=\"l\">        <span class=\"k\">const<\/span> <span class=\"n\">f<\/span> = <span class=\"n\">counts<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">w<\/span>);<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> (!<span class=\"n\">f<\/span>) <span class=\"k\">continue<\/span>;<\/span>\n<span class=\"l\">        <span class=\"n\">score<\/span> += <span class=\"n\">idf<\/span>(<span class=\"n\">w<\/span>) * (<span class=\"n\">f<\/span> * (<span class=\"n\">k1<\/span> + <span class=\"m\">1<\/span>)) \/ (<span class=\"n\">f<\/span> + <span class=\"n\">k1<\/span> * (<span class=\"m\">1<\/span> - <span class=\"n\">b<\/span> + (<span class=\"n\">b<\/span> * <span class=\"n\">toks<\/span>[<span class=\"n\">i<\/span>].<span class=\"n\">length<\/span>) \/ <span class=\"n\">avgLen<\/span>));<\/span>\n<span class=\"l\">      }<\/span>\n<span class=\"l\">      <span class=\"k\">return<\/span> [<span class=\"n\">d<\/span>.<span class=\"n\">id<\/span>, <span class=\"nb\">Number<\/span>(<span class=\"n\">score<\/span>.<span class=\"n\">toFixed<\/span>(<span class=\"m\">2<\/span>))];<\/span>\n<span class=\"l\">    });<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">results<\/span>.<span class=\"n\">filter<\/span>(([, <span class=\"n\">s<\/span>]) =&gt; <span class=\"n\">s<\/span> &gt; <span class=\"m\">0<\/span>).<span class=\"n\">sort<\/span>((<span class=\"n\">x<\/span>, <span class=\"n\">y<\/span>) =&gt; <span class=\"n\">y<\/span>[<span class=\"m\">1<\/span>] - <span class=\"n\">x<\/span>[<span class=\"m\">1<\/span>]).<span class=\"n\">slice<\/span>(<span class=\"m\">0<\/span>, <span class=\"n\">k<\/span>);<\/span>\n<span class=\"l\">  };<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">docs<\/span> = <span class=\"nb\">JSON<\/span>.<span class=\"n\">parse<\/span>(<span class=\"n\">readFileSync<\/span>(<span class=\"s\">\"docs.json\"<\/span>, <span class=\"s\">\"utf8\"<\/span>));<\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">search<\/span> = <span class=\"n\">buildBM25<\/span>(<span class=\"n\">docs<\/span>);<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">q<\/span> <span class=\"k\">of<\/span> [<span class=\"s\">\"error E-1042\"<\/span>, <span class=\"s\">\"can I get my money back?\"<\/span>, <span class=\"s\">\"how do I get a refund\"<\/span>]) {<\/span>\n<span class=\"l\">  <span class=\"nb\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"nb\">JSON<\/span>.<span class=\"n\">stringify<\/span>(<span class=\"n\">q<\/span>).<span class=\"n\">padEnd<\/span>(<span class=\"m\">28<\/span>), <span class=\"s\">\"-&gt;\"<\/span>, <span class=\"nb\">JSON<\/span>.<span class=\"n\">stringify<\/span>(<span class=\"n\">search<\/span>(<span class=\"n\">q<\/span>)));<\/span>\n<span class=\"l\">}<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> node bm25_search.mjs\n&quot;error E-1042&quot;               -&gt; [[&quot;pay-1&quot;,3.23]]\n&quot;can I get my money back?&quot;   -&gt; [[&quot;refund-2&quot;,3.37]]\n&quot;how do I get a refund&quot;      -&gt; [[&quot;refund-1&quot;,2.45]]<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 34, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 2<\/span><span>UTF-8<\/span><span>LF<\/span><span>JavaScript<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Tip: click the <strong>PY<\/strong> \/ <strong>JS<\/strong> tabs and then <strong>\u25b6 Run<\/strong>. This output is from a real run.<\/p>\n<p>Look at the second query. &#8220;can I get my money back?&#8221; found <code>refund-2<\/code> (it contains &#8220;money back&#8221;) but <strong>missed <code>refund-1<\/code><\/strong>, the chunk that actually says you get a full refund within 14 days. That is the synonym problem, and it is exactly where vector search helps.<\/p>\n<div class=\"dd-note\"><strong>Library option:<\/strong> in Python, <code>pip install rank-bm25<\/code> gives you <code>BM25Okapi<\/code> with the same idea. Writing it yourself once helps you understand what the scores mean.<\/div>\n\n<h2 id=\"hybrid-search\">Hybrid search with Reciprocal Rank Fusion (RRF)<\/h2>\n<p>Hybrid search means: run keyword search and vector search for the same question, then merge the two result lists into one. The tricky part is merging. BM25 scores might be 3.37 while cosine similarities are 0.82, so you cannot simply add them. The most popular fix is <strong>Reciprocal Rank Fusion (RRF)<\/strong>, introduced in a <a href=\"https:\/\/plg.uwaterloo.ca\/~gvcormac\/cormacksigir09-rrf.pdf\" target=\"_blank\" rel=\"noopener\">2009 paper by Cormack, Clarke and B\u00fcttcher<\/a>. RRF ignores the raw scores and only looks at <strong>positions<\/strong>:<\/p>\n<p style=\"text-align:center;font-size:1.1em\"><strong>RRF score(chunk) = &#8721; 1 \/ (k + rank)<\/strong>, with k = 60 by default<\/p>\n<p>A chunk ranked #1 in a list gets 1\/61, #2 gets 1\/62, and so on. A chunk that appears in <em>both<\/em> lists adds both numbers together, so chunks that both searches like rise to the top.<\/p>\n\n<figure>\n<svg viewBox=\"0 0 900 340\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Reciprocal Rank Fusion example: keyword list has refund-2 at rank 1; vector list has refund-1, refund-2, billing-1; fused list puts refund-2 first because it appears in both lists\">\n<rect width=\"900\" height=\"340\" rx=\"14\" fill=\"#0f1430\"\/>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<text x=\"450\" y=\"38\" text-anchor=\"middle\" font-size=\"20\" font-weight=\"700\" fill=\"#fff\">How RRF merges two ranked lists<\/text>\n<text x=\"140\" y=\"80\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#a8ecfb\">Keyword list<\/text>\n<rect x=\"40\" y=\"96\" width=\"200\" height=\"40\" rx=\"10\" fill=\"#2a2160\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"60\" y=\"122\" font-size=\"15\" fill=\"#fff\">#1 refund-2<\/text>\n<text x=\"140\" y=\"176\" text-anchor=\"middle\" font-size=\"13\" fill=\"#8f9ad0\">(BM25 found only one)<\/text>\n<text x=\"140\" y=\"214\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#c9bfff\">Vector list<\/text>\n<rect x=\"40\" y=\"226\" width=\"200\" height=\"30\" rx=\"8\" fill=\"#1e2a5a\"\/><text x=\"60\" y=\"246\" font-size=\"14\" fill=\"#fff\">#1 refund-1<\/text>\n<rect x=\"40\" y=\"262\" width=\"200\" height=\"30\" rx=\"8\" fill=\"#2a2160\" stroke=\"#7c5cff\"\/><text x=\"60\" y=\"282\" font-size=\"14\" fill=\"#fff\">#2 refund-2<\/text>\n<rect x=\"40\" y=\"298\" width=\"200\" height=\"30\" rx=\"8\" fill=\"#1e2a5a\"\/><text x=\"60\" y=\"318\" font-size=\"14\" fill=\"#fff\">#3 billing-1<\/text>\n<path d=\"M250 116 C 330 116, 330 180, 400 180\" fill=\"none\" stroke=\"#61dafb\" stroke-width=\"2.5\" stroke-dasharray=\"6 6\"\/>\n<path d=\"M250 260 C 330 260, 330 200, 400 200\" fill=\"none\" stroke=\"#7c5cff\" stroke-width=\"2.5\" stroke-dasharray=\"6 6\"\/>\n<rect x=\"400\" y=\"150\" width=\"120\" height=\"80\" rx=\"16\" fill=\"url(#f2ac)\"\/>\n<defs><linearGradient id=\"f2ac\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0\" stop-color=\"#3178c6\"\/><stop offset=\"1\" stop-color=\"#7c5cff\"\/><\/linearGradient><\/defs>\n<text x=\"460\" y=\"186\" text-anchor=\"middle\" font-size=\"22\" font-weight=\"800\" fill=\"#fff\">RRF<\/text><text x=\"460\" y=\"210\" text-anchor=\"middle\" font-size=\"12\" fill=\"#dfe3ff\">1 \/ (60 + rank)<\/text>\n<path d=\"M520 190 L580 190\" stroke=\"#89e051\" stroke-width=\"3\"\/>\n<text x=\"740\" y=\"80\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#b8f0a0\">Fused list<\/text>\n<rect x=\"590\" y=\"96\" width=\"290\" height=\"48\" rx=\"10\" fill=\"#1b2250\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"606\" y=\"118\" font-size=\"15\" font-weight=\"700\" fill=\"#fff\">1. refund-2 = 0.0325<\/text><text x=\"606\" y=\"136\" font-size=\"12\" fill=\"#8f9ad0\">1\/61 + 1\/62 (in both lists)<\/text>\n<rect x=\"590\" y=\"156\" width=\"290\" height=\"48\" rx=\"10\" fill=\"#1b2250\"\/><text x=\"606\" y=\"178\" font-size=\"15\" fill=\"#fff\">2. refund-1 = 0.0164<\/text><text x=\"606\" y=\"196\" font-size=\"12\" fill=\"#8f9ad0\">1\/61 (vector #1)<\/text>\n<rect x=\"590\" y=\"216\" width=\"290\" height=\"48\" rx=\"10\" fill=\"#1b2250\"\/><text x=\"606\" y=\"238\" font-size=\"15\" fill=\"#fff\">3. billing-1 = 0.0159<\/text><text x=\"606\" y=\"256\" font-size=\"12\" fill=\"#8f9ad0\">1\/63 (vector #3)<\/text>\n<text x=\"735\" y=\"302\" text-anchor=\"middle\" font-size=\"13\" fill=\"#c9d1ff\">Both refund chunks now make the top 2.<\/text>\n<\/g>\n<\/svg>\n<figcaption>RRF only uses positions, so you never need to compare BM25 scores with cosine similarity.<\/figcaption>\n<\/figure>\n\n<p>RRF is only a few lines of code:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: rrf.py, rrf.mjs\">\n<input type=\"radio\" name=\"v2\" id=\"v2f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v2\" id=\"v2f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v2r1\" class=\"r1\">\n<input type=\"checkbox\" id=\"v2r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">rrf.py \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v2f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>rrf.py<\/label>\n<label for=\"v2f2\" class=\"t2\"><b class=\"ic js\">JS<\/b>rrf.mjs<\/label>\n<label for=\"v2r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<label for=\"v2r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a rrf.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">reciprocal_rank_fusion<\/span>(<span class=\"n\">rankings<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">60<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"rankings: lists of doc IDs, best first. Returns IDs sorted by fused score.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">scores<\/span> = {}<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">ranking<\/span> <span class=\"k\">in<\/span> <span class=\"n\">rankings<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">rank<\/span>, <span class=\"n\">doc_id<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">enumerate<\/span>(<span class=\"n\">ranking<\/span>, <span class=\"n\">start<\/span>=<span class=\"m\">1<\/span>):<\/span>\n<span class=\"l\">            <span class=\"n\">scores<\/span>[<span class=\"n\">doc_id<\/span>] = <span class=\"n\">scores<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">doc_id<\/span>, <span class=\"m\">0.0<\/span>) + <span class=\"m\">1<\/span> \/ (<span class=\"n\">k<\/span> + <span class=\"n\">rank<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"nb\">sorted<\/span>(<span class=\"n\">scores<\/span>.<span class=\"n\">items<\/span>(), <span class=\"n\">key<\/span>=<span class=\"k\">lambda<\/span> <span class=\"n\">item<\/span>: <span class=\"n\">item<\/span>[<span class=\"m\">1<\/span>], <span class=\"n\">reverse<\/span>=<span class=\"kc\">True<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">if<\/span> <span class=\"n\">__name__<\/span> == <span class=\"s\">\"__main__\"<\/span>:<\/span>\n<span class=\"l\">    <span class=\"c\"># Query: \"can I get my money back?\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">keyword_hits<\/span> = [<span class=\"s\">\"refund-2\"<\/span>]                          <span class=\"c\"># BM25 (real result above)<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">vector_hits<\/span> = [<span class=\"s\">\"refund-1\"<\/span>, <span class=\"s\">\"refund-2\"<\/span>, <span class=\"s\">\"billing-1\"<\/span>]  <span class=\"c\"># embeddings (example ranking)<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">doc_id<\/span>, <span class=\"n\">score<\/span> <span class=\"k\">in<\/span> <span class=\"n\">reciprocal_rank_fusion<\/span>([<span class=\"n\">keyword_hits<\/span>, <span class=\"n\">vector_hits<\/span>]):<\/span>\n<span class=\"l\">        <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">doc_id<\/span><span class=\"s\">:10} {<\/span><span class=\"n\">score<\/span><span class=\"s\">:.4f}\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python rrf.py\nrefund-2   0.0325\nrefund-1   0.0164\nbilling-1  0.0159<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 15, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a rrf.mjs<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">function<\/span> <span class=\"n\">reciprocalRankFusion<\/span>(<span class=\"n\">rankings<\/span>, <span class=\"n\">k<\/span> = <span class=\"m\">60<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"k\">const<\/span> <span class=\"n\">scores<\/span> = <span class=\"k\">new<\/span> <span class=\"nb\">Map<\/span>();<\/span>\n<span class=\"l\">  <span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> <span class=\"n\">ranking<\/span> <span class=\"k\">of<\/span> <span class=\"n\">rankings<\/span>) {<\/span>\n<span class=\"l\">    <span class=\"n\">ranking<\/span>.<span class=\"n\">forEach<\/span>((<span class=\"n\">docId<\/span>, <span class=\"n\">i<\/span>) =&gt; {<\/span>\n<span class=\"l\">      <span class=\"n\">scores<\/span>.<span class=\"n\">set<\/span>(<span class=\"n\">docId<\/span>, (<span class=\"n\">scores<\/span>.<span class=\"n\">get<\/span>(<span class=\"n\">docId<\/span>) ?? <span class=\"m\">0<\/span>) + <span class=\"m\">1<\/span> \/ (<span class=\"n\">k<\/span> + <span class=\"n\">i<\/span> + <span class=\"m\">1<\/span>));<\/span>\n<span class=\"l\">    });<\/span>\n<span class=\"l\">  }<\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> [...<span class=\"n\">scores<\/span>].<span class=\"n\">sort<\/span>((<span class=\"n\">a<\/span>, <span class=\"n\">b<\/span>) =&gt; <span class=\"n\">b<\/span>[<span class=\"m\">1<\/span>] - <span class=\"n\">a<\/span>[<span class=\"m\">1<\/span>]);<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Query: \"can I get my money back?\"<\/span><\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">keywordHits<\/span> = [<span class=\"s\">\"refund-2\"<\/span>]; <span class=\"c\">\/\/ BM25 (real result above)<\/span><\/span>\n<span class=\"l\"><span class=\"k\">const<\/span> <span class=\"n\">vectorHits<\/span> = [<span class=\"s\">\"refund-1\"<\/span>, <span class=\"s\">\"refund-2\"<\/span>, <span class=\"s\">\"billing-1\"<\/span>]; <span class=\"c\">\/\/ embeddings (example ranking)<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> (<span class=\"k\">const<\/span> [<span class=\"n\">docId<\/span>, <span class=\"n\">score<\/span>] <span class=\"k\">of<\/span> <span class=\"n\">reciprocalRankFusion<\/span>([<span class=\"n\">keywordHits<\/span>, <span class=\"n\">vectorHits<\/span>])) {<\/span>\n<span class=\"l\">  <span class=\"nb\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"n\">docId<\/span>.<span class=\"n\">padEnd<\/span>(<span class=\"m\">10<\/span>), <span class=\"n\">score<\/span>.<span class=\"n\">toFixed<\/span>(<span class=\"m\">4<\/span>));<\/span>\n<span class=\"l\">}<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> node rrf.mjs\nrefund-2   0.0325\nrefund-1   0.0164\nbilling-1  0.0159<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 17, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 2<\/span><span>UTF-8<\/span><span>LF<\/span><span>JavaScript<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Click <strong>\u25b6 Run<\/strong> to see the fused list. The vector ranking here is an example list so the code runs without any model; the next example uses a real embedding model.<\/p>\n\n<h3>Full hybrid search with real embeddings (Ollama)<\/h3>\n<p>Now let&#8217;s combine the BM25 class with real vector search. We use the free local embedding model <code>nomic-embed-text<\/code> through Ollama, which you set up in <a href=\"https:\/\/devdojo.co.in\/?p=281\">Part 6<\/a>. First install what you need:<\/p>\n<div class=\"dd-vsc dd-vsc-termonly\" role=\"group\" aria-label=\"Terminal: Terminal \u2014 install for hybrid search and re-ranking\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">Terminal \u2014 install for hybrid search and re-ranking<\/span><\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"c\"># Python packages (Node.js users: npm install ollama)<\/span><\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> pip install ollama sentence-transformers<\/span>\n<span class=\"l\"><span class=\"c\"># Free local models for embeddings and for query rewriting<\/span><\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> ollama pull nomic-embed-text<\/span>\n<span class=\"l\"><span class=\"gp\">$<\/span> ollama pull llama3.2<\/span><\/code><\/pre>\n<\/div>\n<p>Put <code>hybrid_search.py<\/code> in the same folder as <code>bm25_search.py<\/code>, <code>rrf.py<\/code> and <code>docs.json<\/code>:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: hybrid_search.py\">\n<input type=\"radio\" name=\"v3\" id=\"v3f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v3r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">hybrid_search.py \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v3f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>hybrid_search.py<\/label>\n<label for=\"v3r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a hybrid_search.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">ollama<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">bm25_search<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">BM25<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">rrf<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">reciprocal_rank_fusion<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">docs<\/span> = <span class=\"n\">json<\/span>.<span class=\"n\">load<\/span>(<span class=\"nb\">open<\/span>(<span class=\"s\">\"docs.json\"<\/span>))<\/span>\n<span class=\"l\"><span class=\"n\">bm25<\/span> = <span class=\"n\">BM25<\/span>(<span class=\"n\">docs<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">embed<\/span>(<span class=\"n\">texts<\/span>):<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">ollama<\/span>.<span class=\"n\">embed<\/span>(<span class=\"n\">model<\/span>=<span class=\"s\">\"nomic-embed-text\"<\/span>, <span class=\"nb\">input<\/span>=<span class=\"n\">texts<\/span>)[<span class=\"s\">\"embeddings\"<\/span>]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">cosine<\/span>(<span class=\"n\">a<\/span>, <span class=\"n\">b<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">dot<\/span> = <span class=\"nb\">sum<\/span>(<span class=\"n\">x<\/span> * <span class=\"n\">y<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span>, <span class=\"n\">y<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">zip<\/span>(<span class=\"n\">a<\/span>, <span class=\"n\">b<\/span>))<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">dot<\/span> \/ ((<span class=\"nb\">sum<\/span>(<span class=\"n\">x<\/span> * <span class=\"n\">x<\/span> <span class=\"k\">for<\/span> <span class=\"n\">x<\/span> <span class=\"k\">in<\/span> <span class=\"n\">a<\/span>) ** <span class=\"m\">0.5<\/span>) * (<span class=\"nb\">sum<\/span>(<span class=\"n\">y<\/span> * <span class=\"n\">y<\/span> <span class=\"k\">for<\/span> <span class=\"n\">y<\/span> <span class=\"k\">in<\/span> <span class=\"n\">b<\/span>) ** <span class=\"m\">0.5<\/span>))<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">doc_vectors<\/span> = <span class=\"n\">embed<\/span>([<span class=\"s\">\"search_document: \"<\/span> + <span class=\"n\">d<\/span>[<span class=\"s\">\"text\"<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">d<\/span> <span class=\"k\">in<\/span> <span class=\"n\">docs<\/span>])<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">vector_search<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">5<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">q<\/span> = <span class=\"n\">embed<\/span>([<span class=\"s\">\"search_query: \"<\/span> + <span class=\"n\">query<\/span>])[<span class=\"m\">0<\/span>]<\/span>\n<span class=\"l\">    <span class=\"n\">scored<\/span> = <span class=\"nb\">sorted<\/span>(<span class=\"nb\">zip<\/span>(<span class=\"n\">docs<\/span>, <span class=\"n\">doc_vectors<\/span>), <span class=\"n\">key<\/span>=<span class=\"k\">lambda<\/span> <span class=\"n\">p<\/span>: <span class=\"n\">cosine<\/span>(<span class=\"n\">q<\/span>, <span class=\"n\">p<\/span>[<span class=\"m\">1<\/span>]), <span class=\"n\">reverse<\/span>=<span class=\"kc\">True<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">d<\/span>[<span class=\"s\">\"id\"<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">d<\/span>, <span class=\"n\">_<\/span> <span class=\"k\">in<\/span> <span class=\"n\">scored<\/span>[:<span class=\"n\">k<\/span>]]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">hybrid_search<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">3<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">keyword_ids<\/span> = [<span class=\"n\">doc_id<\/span> <span class=\"k\">for<\/span> <span class=\"n\">doc_id<\/span>, <span class=\"n\">_<\/span> <span class=\"k\">in<\/span> <span class=\"n\">bm25<\/span>.<span class=\"n\">search<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">5<\/span>)]<\/span>\n<span class=\"l\">    <span class=\"n\">vector_ids<\/span> = <span class=\"n\">vector_search<\/span>(<span class=\"n\">query<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">5<\/span>)<\/span>\n<span class=\"l\">    <span class=\"n\">fused<\/span> = <span class=\"n\">reciprocal_rank_fusion<\/span>([<span class=\"n\">keyword_ids<\/span>, <span class=\"n\">vector_ids<\/span>])<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">doc_id<\/span> <span class=\"k\">for<\/span> <span class=\"n\">doc_id<\/span>, <span class=\"n\">_<\/span> <span class=\"k\">in<\/span> <span class=\"n\">fused<\/span>[:<span class=\"n\">k<\/span>]]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">q<\/span> <span class=\"k\">in<\/span> [<span class=\"s\">\"error E-1042\"<\/span>, <span class=\"s\">\"can I get my money back?\"<\/span>]:<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"n\">q<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">\"  keyword:\"<\/span>, [<span class=\"n\">i<\/span> <span class=\"k\">for<\/span> <span class=\"n\">i<\/span>, <span class=\"n\">_<\/span> <span class=\"k\">in<\/span> <span class=\"n\">bm25<\/span>.<span class=\"n\">search<\/span>(<span class=\"n\">q<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">3<\/span>)])<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">\"  vector: \"<\/span>, <span class=\"n\">vector_search<\/span>(<span class=\"n\">q<\/span>, <span class=\"n\">k<\/span>=<span class=\"m\">3<\/span>))<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">\"  hybrid: \"<\/span>, <span class=\"n\">hybrid_search<\/span>(<span class=\"n\">q<\/span>))<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><span class=\"dd-term-note\">Example output \u2013 your vector ranking may differ<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python hybrid_search.py\nerror E-1042\n  keyword: [&#x27;pay-1&#x27;]\n  vector:  [&#x27;pay-1&#x27;, &#x27;pay-2&#x27;, &#x27;support-1&#x27;]\n  hybrid:  [&#x27;pay-1&#x27;, &#x27;pay-2&#x27;, &#x27;support-1&#x27;]\ncan I get my money back?\n  keyword: [&#x27;refund-2&#x27;]\n  vector:  [&#x27;refund-1&#x27;, &#x27;refund-2&#x27;, &#x27;billing-1&#x27;]\n  hybrid:  [&#x27;refund-2&#x27;, &#x27;refund-1&#x27;, &#x27;billing-1&#x27;]<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 33, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p>The vector list catches <code>refund-1<\/code> for &#8220;money back&#8221;, the keyword list makes sure the exact code <code>E-1042<\/code> always wins, and RRF keeps the best of both. Notice the <code>search_document:<\/code> and <code>search_query:<\/code> prefixes: the <code>nomic-embed-text<\/code> model is trained to use them, and they improve results.<\/p>\n<div class=\"dd-tip\"><strong>Weighting:<\/strong> if your users mostly type codes and names, give the keyword list more weight: multiply its RRF part by 1.5, or fetch more keyword results. Many vector databases call this setting <code>alpha<\/code> (0 = only keyword, 1 = only vector).<\/div>\n\n<h2 id=\"rerank\">Re-ranking with a cross-encoder<\/h2>\n<p>Hybrid search gives you a good list of <em>candidates<\/em>, but the order is still rough. A <strong>re-ranker<\/strong> is a second model that reads the question and each candidate chunk <em>together<\/em> and gives a precise relevance score. Then you keep only the best few.<\/p>\n<p>Why is that better? The embedding model you used for vector search is a <strong>bi-encoder<\/strong>: it turns the question and the chunk into vectors <em>separately<\/em>, and only compares them at the end. That is fast (chunk vectors are computed once and stored), but the model never sees both texts side by side. A <strong>cross-encoder<\/strong> reads &#8220;question + chunk&#8221; as one input, so it can notice details like &#8220;within 14 days&#8221; answering &#8220;can I get my money back?&#8221;. It is too slow to run on your whole database, but perfect for re-ordering the top 20&#8211;50 results.<\/p>\n\n<figure>\n<svg viewBox=\"0 0 900 300\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Bi-encoder versus cross-encoder: a bi-encoder embeds the question and the chunk separately and compares vectors, fast for millions of chunks; a cross-encoder reads question and chunk together and outputs one relevance score, accurate for the top 50\">\n<rect width=\"900\" height=\"300\" rx=\"14\" fill=\"#0f1430\"\/>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<text x=\"225\" y=\"38\" text-anchor=\"middle\" font-size=\"19\" font-weight=\"700\" fill=\"#c9bfff\">Bi-encoder (vector search)<\/text>\n<rect x=\"40\" y=\"62\" width=\"150\" height=\"40\" rx=\"10\" fill=\"#1e2a5a\"\/><text x=\"115\" y=\"88\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">question<\/text>\n<rect x=\"260\" y=\"62\" width=\"150\" height=\"40\" rx=\"10\" fill=\"#1e2a5a\"\/><text x=\"335\" y=\"88\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">chunk<\/text>\n<rect x=\"40\" y=\"128\" width=\"150\" height=\"40\" rx=\"10\" fill=\"#7c5cff\"\/><text x=\"115\" y=\"154\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">model \u2192 vector<\/text>\n<rect x=\"260\" y=\"128\" width=\"150\" height=\"40\" rx=\"10\" fill=\"#7c5cff\"\/><text x=\"335\" y=\"154\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">model \u2192 vector<\/text>\n<path d=\"M115 102V128M335 102V128M115 168 L225 200 M335 168 L225 200\" stroke=\"#9fb2ff\" stroke-width=\"2\" fill=\"none\"\/>\n<rect x=\"150\" y=\"200\" width=\"150\" height=\"38\" rx=\"10\" fill=\"#151b3b\" stroke=\"#7c5cff\"\/><text x=\"225\" y=\"224\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">cosine similarity<\/text>\n<text x=\"225\" y=\"272\" text-anchor=\"middle\" font-size=\"14\" fill=\"#89e051\">Fast: search millions of chunks<\/text>\n<line x1=\"450\" y1=\"30\" x2=\"450\" y2=\"280\" stroke=\"#2b3466\" stroke-width=\"2\"\/>\n<text x=\"675\" y=\"38\" text-anchor=\"middle\" font-size=\"19\" font-weight=\"700\" fill=\"#ffd28a\">Cross-encoder (re-ranker)<\/text>\n<rect x=\"520\" y=\"62\" width=\"310\" height=\"40\" rx=\"10\" fill=\"#1e2a5a\"\/><text x=\"675\" y=\"88\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">question + chunk (read together)<\/text>\n<rect x=\"560\" y=\"128\" width=\"230\" height=\"40\" rx=\"10\" fill=\"#e08a00\"\/><text x=\"675\" y=\"154\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#1e1e1e\">model reads both<\/text>\n<path d=\"M675 102V128M675 168V200\" stroke=\"#ffd28a\" stroke-width=\"2\"\/>\n<rect x=\"590\" y=\"200\" width=\"170\" height=\"38\" rx=\"10\" fill=\"#151b3b\" stroke=\"#e08a00\"\/><text x=\"675\" y=\"224\" text-anchor=\"middle\" font-size=\"14\" fill=\"#fff\">relevance score<\/text>\n<text x=\"675\" y=\"272\" text-anchor=\"middle\" font-size=\"14\" fill=\"#ffd28a\">Accurate: use on the top 20\u201350 only<\/text>\n<\/g>\n<\/svg>\n<figcaption>Use the fast bi-encoder to find candidates, then the careful cross-encoder to order them.<\/figcaption>\n<\/figure>\n\n<p>The <a href=\"https:\/\/sbert.net\/docs\/cross_encoder\/usage\/usage.html\" target=\"_blank\" rel=\"noopener\">sentence-transformers library<\/a> includes free cross-encoder models. <code>cross-encoder\/ms-marco-MiniLM-L6-v2<\/code> is small enough to run on a laptop CPU:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: rerank.py\">\n<input type=\"radio\" name=\"v4\" id=\"v4f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v4r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">rerank.py \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v4f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>rerank.py<\/label>\n<label for=\"v4r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a rerank.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">sentence_transformers<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">CrossEncoder<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">docs<\/span> = {<span class=\"n\">d<\/span>[<span class=\"s\">\"id\"<\/span>]: <span class=\"n\">d<\/span>[<span class=\"s\">\"text\"<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">d<\/span> <span class=\"k\">in<\/span> <span class=\"n\">json<\/span>.<span class=\"n\">load<\/span>(<span class=\"nb\">open<\/span>(<span class=\"s\">\"docs.json\"<\/span>))}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># A small, free re-ranker model (downloads about 90 MB the first time)<\/span><\/span>\n<span class=\"l\"><span class=\"n\">reranker<\/span> = <span class=\"n\">CrossEncoder<\/span>(<span class=\"s\">\"cross-encoder\/ms-marco-MiniLM-L6-v2\"<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">query<\/span> = <span class=\"s\">\"can I get my money back?\"<\/span><\/span>\n<span class=\"l\"><span class=\"n\">candidates<\/span> = [<span class=\"s\">\"refund-2\"<\/span>, <span class=\"s\">\"refund-1\"<\/span>, <span class=\"s\">\"billing-1\"<\/span>, <span class=\"s\">\"pay-2\"<\/span>, <span class=\"s\">\"support-1\"<\/span>]  <span class=\"c\"># top 5 from hybrid search<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">results<\/span> = <span class=\"n\">reranker<\/span>.<span class=\"n\">rank<\/span>(<span class=\"n\">query<\/span>, [<span class=\"n\">docs<\/span>[<span class=\"n\">i<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">i<\/span> <span class=\"k\">in<\/span> <span class=\"n\">candidates<\/span>], <span class=\"n\">top_k<\/span>=<span class=\"m\">3<\/span>)<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">place<\/span>, <span class=\"n\">r<\/span> <span class=\"k\">in<\/span> <span class=\"nb\">enumerate<\/span>(<span class=\"n\">results<\/span>, <span class=\"n\">start<\/span>=<span class=\"m\">1<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">doc_id<\/span> = <span class=\"n\">candidates<\/span>[<span class=\"n\">r<\/span>[<span class=\"s\">\"corpus_id\"<\/span>]]  <span class=\"c\"># r[\"score\"] holds the relevance score<\/span><\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">place<\/span><span class=\"s\">}. {<\/span><span class=\"n\">doc_id<\/span><span class=\"s\">:10} {<\/span><span class=\"n\">docs<\/span>[<span class=\"n\">doc_id<\/span>][:<span class=\"m\">52<\/span>]<span class=\"s\">}...\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><span class=\"dd-term-note\">Example output \u2013 order shown, scores vary by model version<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python rerank.py\n1. refund-1   Refund policy: you can ask for a full refund within ...\n2. refund-2   After 14 days money back is not possible, but you ca...\n3. billing-1  To cancel your subscription, open Settings, then Bil...<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 15, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p>The re-ranker moves <code>refund-1<\/code> (&#8220;full refund within 14 days&#8221;) to the top, because it directly answers the question. Our hybrid list had it in second place. That one change can be the difference between a correct and a wrong answer from the LLM.<\/p>\n<div class=\"dd-note\"><strong>Hosted options:<\/strong> if you prefer an API, Cohere Rerank, Voyage AI and Jina AI offer re-ranking endpoints. The pattern is the same: send the query plus 20&#8211;50 candidate texts, get back scores, keep the top few. Bigger open models like <code>BAAI\/bge-reranker-v2-m3<\/code> are more accurate and support many languages, including Hindi.<\/div>\n\n<h2 id=\"rewrite\">Query rewriting: multi-query and HyDE<\/h2>\n<p>Sometimes the problem is not the search but the <strong>question<\/strong>. Users type short, vague or follow-up questions like &#8220;can I still get my money back for it?&#8221;. What is &#8220;it&#8221;? Query rewriting asks an LLM to fix the question <em>before<\/em> searching. Three common techniques:<\/p>\n<ul>\n<li><strong>Stand-alone rewrite:<\/strong> use the chat history to replace &#8220;it&#8221;, &#8220;that&#8221; or &#8220;the same&#8221; with the real subject (&#8220;DevDojo Pro bought last week&#8221;).<\/li>\n<li><strong>Multi-query:<\/strong> create 3 different versions of the question (&#8220;refund policy&#8221;, &#8220;cancel and get money back&#8221;&#8230;), search with each, and fuse all result lists with RRF. Different words find different chunks.<\/li>\n<li><strong>HyDE (Hypothetical Document Embeddings):<\/strong> ask the LLM to write a short <em>fake answer<\/em>, then search with that answer. A fake answer &#8220;looks like&#8221; a real help-centre chunk, so its embedding lands closer to the right chunks than the short question does.<\/li>\n<\/ul>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: rewrite_query.py\">\n<input type=\"radio\" name=\"v5\" id=\"v5f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v5r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">rewrite_query.py \u2014 devdojo-better-rag \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v5f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>rewrite_query.py<\/label>\n<label for=\"v5r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-better-rag \u203a rewrite_query.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">ollama<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">MODEL<\/span> = <span class=\"s\">\"llama3.2\"<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">multi_query<\/span>(<span class=\"n\">question<\/span>, <span class=\"n\">history<\/span>=<span class=\"s\">\"\"<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">prompt<\/span> = (<\/span>\n<span class=\"l\">        <span class=\"s\">\"Rewrite the user's question as 3 short search queries for a help-centre search.\\n\"<\/span><\/span>\n<span class=\"l\">        <span class=\"s\">\"Use the chat history to replace words like 'it' or 'that'. \"<\/span><\/span>\n<span class=\"l\">        <span class=\"s\">\"Use different words in each query. Return one query per line, nothing else.\\n\\n\"<\/span><\/span>\n<span class=\"l\">        <span class=\"s\">f\"Chat history:\\n{<\/span><span class=\"n\">history<\/span> <span class=\"k\">or<\/span> <span class=\"s\">'(none)'}\\n\\nQuestion: {<\/span><span class=\"n\">question<\/span><span class=\"s\">}\"<\/span><\/span>\n<span class=\"l\">    )<\/span>\n<span class=\"l\">    <span class=\"n\">reply<\/span> = <span class=\"n\">ollama<\/span>.<span class=\"n\">chat<\/span>(<span class=\"n\">model<\/span>=<span class=\"n\">MODEL<\/span>, <span class=\"n\">messages<\/span>=[{<span class=\"s\">\"role\"<\/span>: <span class=\"s\">\"user\"<\/span>, <span class=\"s\">\"content\"<\/span>: <span class=\"n\">prompt<\/span>}],<\/span>\n<span class=\"l\">                        <span class=\"n\">options<\/span>={<span class=\"s\">\"temperature\"<\/span>: <span class=\"m\">0<\/span>})<\/span>\n<span class=\"l\">    <span class=\"n\">lines<\/span> = [<span class=\"n\">l<\/span>.<span class=\"n\">strip<\/span>(<span class=\"s\">\"-\u2022 \"<\/span>).<span class=\"n\">strip<\/span>() <span class=\"k\">for<\/span> <span class=\"n\">l<\/span> <span class=\"k\">in<\/span> <span class=\"n\">reply<\/span>.<span class=\"n\">message<\/span>.<span class=\"n\">content<\/span>.<span class=\"n\">splitlines<\/span>()]<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">question<\/span>] + [<span class=\"n\">l<\/span> <span class=\"k\">for<\/span> <span class=\"n\">l<\/span> <span class=\"k\">in<\/span> <span class=\"n\">lines<\/span> <span class=\"k\">if<\/span> <span class=\"n\">l<\/span>][:<span class=\"m\">3<\/span>]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">hyde<\/span>(<span class=\"n\">question<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"HyDE: write a fake answer, then search with it instead of the question.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">reply<\/span> = <span class=\"n\">ollama<\/span>.<span class=\"n\">chat<\/span>(<span class=\"n\">model<\/span>=<span class=\"n\">MODEL<\/span>, <span class=\"n\">messages<\/span>=[{<span class=\"s\">\"role\"<\/span>: <span class=\"s\">\"user\"<\/span>, <span class=\"s\">\"content\"<\/span>:<\/span>\n<span class=\"l\">        <span class=\"s\">f\"Write a 2-sentence help-centre answer to: {<\/span><span class=\"n\">question<\/span><span class=\"s\">}\"<\/span>}])<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">reply<\/span>.<span class=\"n\">message<\/span>.<span class=\"n\">content<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">history<\/span> = <span class=\"s\">\"User: I bought DevDojo Pro last week.\\nBot: Great! How can I help?\"<\/span><\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">q<\/span> <span class=\"k\">in<\/span> <span class=\"n\">multi_query<\/span>(<span class=\"s\">\"can I still get my money back for it?\"<\/span>, <span class=\"n\">history<\/span>):<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">\"query:\"<\/span>, <span class=\"n\">q<\/span>)<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">\"hyde :\"<\/span>, <span class=\"n\">hyde<\/span>(<span class=\"s\">\"can I get my money back?\"<\/span>)[:<span class=\"m\">90<\/span>], <span class=\"s\">\"...\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><span class=\"dd-term-note\">Example output \u2013 LLM wording will differ<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python rewrite_query.py\nquery: can I still get my money back for it?\nquery: DevDojo Pro refund policy\nquery: refund for DevDojo Pro bought last week\nquery: cancel DevDojo Pro and get money back\nhyde : You can ask for a full refund within 14 days of buying DevDojo Pro. After that, you can ...<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 26, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<div class=\"dd-warn\"><strong>Watch out:<\/strong> the HyDE answer is <em>only<\/em> used for searching. Never show it to the user, because the LLM may invent details. The final answer must still come from the real chunks you retrieve.<\/div>\n\n<h2 id=\"which\">Which fix solves which problem?<\/h2>\n<p>You don&#8217;t need every technique in every app. Pick the problem you see in your tests:<\/p>\n<div class=\"dd-tabs\">\n<input type=\"radio\" name=\"ddt\" id=\"ti1\" checked><input type=\"radio\" name=\"ddt\" id=\"ti2\"><input type=\"radio\" name=\"ddt\" id=\"ti3\"><input type=\"radio\" name=\"ddt\" id=\"ti4\">\n<div class=\"labels\"><label for=\"ti1\">Exact codes missed<\/label><label for=\"ti2\">Right chunk at #6<\/label><label for=\"ti3\">Vague follow-ups<\/label><label for=\"ti4\">Synonyms missed<\/label><\/div>\n<div class=\"panel p1\"><p><strong>Symptom:<\/strong> users search for &#8220;E-1042&#8221;, an invoice number or a function name like <code>useEffect<\/code>, and the answer is wrong.<\/p><p><strong>Fix:<\/strong> add <strong>BM25 keyword search<\/strong> and use <strong>hybrid search with RRF<\/strong>. Keep codes intact when you tokenize (do not split &#8220;E-1042&#8221; into &#8220;e&#8221; and &#8220;1042&#8221;).<\/p><\/div>\n<div class=\"panel p2\"><p><strong>Symptom:<\/strong> the right chunk is in your top 10, but not in the top 3 that you send to the LLM.<\/p><p><strong>Fix:<\/strong> retrieve more candidates (20&#8211;50), then <strong>re-rank with a cross-encoder<\/strong> and keep the top 3&#8211;5.<\/p><\/div>\n<div class=\"panel p3\"><p><strong>Symptom:<\/strong> the first question works, but follow-ups like &#8220;and for the yearly plan?&#8221; return random chunks.<\/p><p><strong>Fix:<\/strong> <strong>rewrite the question into a stand-alone query<\/strong> using the chat history before you search.<\/p><\/div>\n<div class=\"panel p4\"><p><strong>Symptom:<\/strong> the user&#8217;s words differ from your documents&#8217; words (&#8220;money back&#8221; vs &#8220;refund&#8221;, &#8220;login issue&#8221; vs &#8220;authentication error&#8221;).<\/p><p><strong>Fix:<\/strong> make sure <strong>vector search<\/strong> is part of your hybrid search, and try <strong>multi-query<\/strong> or <strong>HyDE<\/strong> for short questions.<\/p><\/div>\n<\/div>\n\n<h2 id=\"pipeline\">The full retrieval pipeline<\/h2>\n<p>Put together, a strong retrieval step for RAG usually looks like this:<\/p>\n<ol>\n<li><strong>Rewrite<\/strong> the user&#8217;s question into a clear, stand-alone query (optional: create 2&#8211;3 variations).<\/li>\n<li><strong>Search wide:<\/strong> BM25 top 20 + vector top 20 for each query.<\/li>\n<li><strong>Fuse<\/strong> all lists with RRF.<\/li>\n<li><strong>Re-rank<\/strong> the top 20&#8211;50 fused results with a cross-encoder.<\/li>\n<li><strong>Send<\/strong> the top 3&#8211;5 chunks (with their source and section) to the LLM, as in Part 11.<\/li>\n<\/ol>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Step<\/th><th>Extra time per question<\/th><th>Extra cost<\/th><th>When to add it<\/th><\/tr><\/thead>\n<tbody>\n<tr><td>Hybrid search (BM25 + vector + RRF)<\/td><td>Very small<\/td><td>None<\/td><td>Almost always. Start here.<\/td><\/tr>\n<tr><td>Re-ranking (cross-encoder)<\/td><td>Small to medium (depends on model and number of candidates)<\/td><td>Free locally, or a small API fee<\/td><td>When the right chunk is often in the top 10 but not the top 3.<\/td><\/tr>\n<tr><td>Stand-alone rewrite<\/td><td>One extra LLM call<\/td><td>One small LLM call<\/td><td>Any chat app with follow-up questions.<\/td><\/tr>\n<tr><td>Multi-query \/ HyDE<\/td><td>One LLM call + extra searches<\/td><td>One small LLM call<\/td><td>Short or vague questions; test it first.<\/td><\/tr>\n<\/tbody><\/table><\/div>\n<div class=\"dd-tip\"><strong>Measure, don&#8217;t guess:<\/strong> reuse the test questions from Part 12. Count how often the correct chunk appears in the top 3 (this is called <em>hit rate @3<\/em>) for: vector only, hybrid, and hybrid + re-rank. Keep a step only if it improves the number. We will build proper evaluations in Part 19.<\/div>\n\n<h2 id=\"databases\">Hybrid search in vector databases<\/h2>\n<p>You don&#8217;t have to build everything by hand in production. Many databases from <a href=\"https:\/\/devdojo.co.in\/?p=310\">Part 10<\/a> support hybrid search directly:<\/p>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Database<\/th><th>How hybrid search works<\/th><\/tr><\/thead>\n<tbody>\n<tr><td>PostgreSQL + pgvector<\/td><td>Run a full-text search query (<code>tsvector<\/code> \/ <code>ts_rank<\/code>) and a pgvector query, then combine them with RRF in SQL or in your app code.<\/td><\/tr>\n<tr><td>Elasticsearch \/ OpenSearch<\/td><td>BM25 is built in; add a vector field and combine both with their hybrid or RRF features.<\/td><\/tr>\n<tr><td>Weaviate<\/td><td>Has a <code>hybrid<\/code> query with an <code>alpha<\/code> setting to balance keyword and vector results.<\/td><\/tr>\n<tr><td>Qdrant<\/td><td>Store dense and sparse vectors together and fuse them with RRF in its query API.<\/td><\/tr>\n<tr><td>Pinecone<\/td><td>Supports sparse + dense vectors for hybrid search.<\/td><\/tr>\n<\/tbody><\/table><\/div>\n<p>Features change quickly, so check your database&#8217;s current docs. The idea is always the same as the code above: two ranked lists, one fused list.<\/p>\n\n<h2 id=\"errors\">Common errors and fixes<\/h2>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Problem<\/th><th>Why it happens<\/th><th>Fix<\/th><\/tr><\/thead>\n<tbody>\n<tr><td>BM25 finds nothing for &#8220;E-1042&#8221;<\/td><td>The tokenizer split the code into &#8220;e&#8221; and &#8220;1042&#8221;, or removed it<\/td><td>Use a regex that keeps hyphenated words, like <code>[a-z0-9]+(?:-[a-z0-9]+)*<\/code><\/td><\/tr>\n<tr><td>Hybrid results look worse than vector only<\/td><td>You added raw BM25 scores to cosine scores (different scales)<\/td><td>Use RRF on ranks, or normalise both scores to 0&#8211;1 first<\/td><\/tr>\n<tr><td><code>ConnectionError<\/code> \/ connection refused from <code>ollama<\/code><\/td><td>The Ollama app or server is not running<\/td><td>Start Ollama (<code>ollama serve<\/code>) and run <code>ollama list<\/code> to check models<\/td><\/tr>\n<tr><td><code>model \"nomic-embed-text\" not found<\/code><\/td><td>The model was never pulled<\/td><td><code>ollama pull nomic-embed-text<\/code><\/td><\/tr>\n<tr><td>Re-ranking is very slow<\/td><td>Too many candidates, or a large model on CPU<\/td><td>Re-rank only the top 20&#8211;50; use a small model like MiniLM; use a GPU or a hosted API<\/td><\/tr>\n<tr><td>Re-ranker downloads fail<\/td><td>No internet access to Hugging Face, or a firewall<\/td><td>Download the model once on a machine with access and load it from a local folder<\/td><\/tr>\n<tr><td>Multi-query returns the same query 3 times<\/td><td>The prompt doesn&#8217;t ask for different words<\/td><td>Ask for &#8220;different words in each query&#8221; and use temperature 0&#8211;0.3<\/td><\/tr>\n<tr><td>The LLM answer quotes the HyDE text<\/td><td>The fake answer was sent to the LLM as context<\/td><td>Use HyDE text only for searching; send the real chunks<\/td><\/tr>\n<\/tbody><\/table><\/div>\n\n<h2 id=\"best\">Best practices<\/h2>\n<ul>\n<li><strong>Start with hybrid search.<\/strong> It is cheap, fast and fixes the most common failures.<\/li>\n<li><strong>Retrieve wide, then narrow.<\/strong> Get 20&#8211;50 candidates, re-rank, then send only 3&#8211;5 chunks to the LLM. Fewer, better chunks give clearer answers and cost less.<\/li>\n<li><strong>Keep metadata with every result<\/strong> (source, page, section) so the final answer can cite where it came from.<\/li>\n<li><strong>Use the same tokenizer<\/strong> for indexing and searching in BM25, and lowercase both.<\/li>\n<li><strong>Cache<\/strong> query rewrites and embeddings for common questions to save time and money.<\/li>\n<li><strong>Test with real user questions,<\/strong> including typos, Hinglish (&#8220;refund kaise milega&#8221;) and follow-ups, not only the clean ones you wrote yourself.<\/li>\n<li><strong>Add one technique at a time<\/strong> and measure hit rate @3 after each change.<\/li>\n<\/ul>\n\n<h2 id=\"practice\">Practice task<\/h2>\n<div class=\"dd-tip\">\n<p><strong>Upgrade your RAG app:<\/strong><\/p>\n<ol>\n<li>Add 5 chunks of your own to <code>docs.json<\/code>, including one with a code or ID (an order number, an error code or a version number).<\/li>\n<li>Run <code>bm25_search.py<\/code> and <code>hybrid_search.py<\/code> with 5 questions. Write down which chunk each method puts first.<\/li>\n<li>Change the RRF <code>k<\/code> from 60 to 10. Does the order change?<\/li>\n<li>Add <code>rerank.py<\/code> after hybrid search. Count how often the correct chunk is in the top 3 before and after re-ranking.<\/li>\n<li>Bonus: plug the full pipeline (rewrite &#8594; hybrid &#8594; re-rank) into the Ollama RAG app from <a href=\"https:\/\/devdojo.co.in\/?p=313\">Part 11<\/a> and use the chunks from <a href=\"https:\/\/devdojo.co.in\/?p=315\">Part 12<\/a>.<\/li>\n<\/ol>\n<\/div>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Most bad RAG answers are really <em>retrieval<\/em> problems. Hybrid search lets keyword search and vector search cover each other&#8217;s blind spots, RRF merges them without any score maths, a cross-encoder re-ranker puts the best chunk on top, and query rewriting turns vague follow-ups into clear searches. Add them one at a time, measure with your test questions, and your RAG app will find the right chunk far more often.<\/p>\n\n<div class=\"dd-next\"><strong>Next part &#8594; Part 14: Function Calling and Tool Use.<\/strong> So far our LLM can only read text we give it. Next, you will let it call your own functions to check order status, do maths or fetch live data, and return the results in its answer.<\/div>\n\n<div class=\"dd-cta\">\n<h3>New posts every day on DevDojo<\/h3>\n<p>Follow the full <strong>Generative AI series<\/strong> from basics to production. Bookmark <a href=\"https:\/\/devdojo.co.in\/\">devdojo.co.in<\/a> and open the roadmap above to see what is coming next.<\/p>\n<\/div>\n\n<h2 id=\"faq\">FAQ<\/h2>\n<details><summary>What is hybrid search in RAG?<\/summary><p>Hybrid search runs keyword search (usually BM25) and vector search for the same question and merges the two result lists. Keyword search finds exact words like codes and names; vector search finds similar meanings. Together they retrieve the right chunk more often than either one alone.<\/p><\/details>\n<details><summary>What is Reciprocal Rank Fusion (RRF)?<\/summary><p>RRF is a simple way to merge ranked lists. Each chunk gets 1 \/ (k + rank) from every list it appears in, with k usually 60, and the totals decide the final order. Because it uses positions instead of raw scores, it works even when the two searches score on different scales.<\/p><\/details>\n<details><summary>What is the difference between a bi-encoder and a cross-encoder?<\/summary><p>A bi-encoder turns the question and each chunk into vectors separately and compares them, which is fast enough to search millions of chunks. A cross-encoder reads the question and one chunk together and outputs a relevance score. It is more accurate but slower, so it is used to re-rank the top 20&#8211;50 results.<\/p><\/details>\n<details><summary>Does re-ranking make RAG slower?<\/summary><p>A little. A small cross-encoder re-ranking 20&#8211;50 short chunks adds a small delay on a CPU and very little on a GPU. Keep the candidate list short and the model small, and measure the delay in your own app.<\/p><\/details>\n<details><summary>What is HyDE in RAG?<\/summary><p>HyDE stands for Hypothetical Document Embeddings. The LLM writes a short fake answer to the question, and you search with the embedding of that answer instead of the question. It often helps short or vague questions. The fake answer is only used for searching, never shown to users.<\/p><\/details>\n<details><summary>Do I need LangChain or LlamaIndex for hybrid search?<\/summary><p>No. As shown above, BM25 and RRF are each about 20&#8211;30 lines of code. Frameworks offer ready-made retrievers (for example an ensemble retriever that uses RRF) which can save time in bigger projects. We compare them in Part 18.<\/p><\/details>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.<\/p>\n","protected":false},"author":1,"featured_media":318,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[178,176,52,179,86,177,112],"class_list":["post-319","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","tag-bm25","tag-hybrid-search","tag-python","tag-query-rewriting","tag-rag","tag-re-ranking","tag-series-generative-ai"],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 5.0.4 - aioseo.com -->\n\t<meta name=\"description\" content=\"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.\" \/>\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"Lokendra\"\/>\n\t<link rel=\"canonical\" href=\"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/\" \/>\n\t\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 5.0.4\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"DevDojo - Empowering Developers\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"GenAI Part 13: Hybrid Search &amp; Re-ranking for RAG\" \/>\n\t\t<meta property=\"og:description\" content=\"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2026-12-01T14:38:26+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2026-12-01T14:38:27+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n\t\t<meta name=\"twitter:title\" content=\"GenAI Part 13: Hybrid Search &amp; Re-ranking for RAG\" \/>\n\t\t<meta name=\"twitter:description\" content=\"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.\" \/>\n\t\t<script type=\"application\/ld+json\" class=\"aioseo-schema\">\n\t\t\t{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"BlogPosting\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#blogposting\",\"name\":\"Hybrid Search, Re-ranking & Query Rewriting for RAG\",\"headline\":\"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting\",\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/genai-series-part-13-hybrid-search-reranking.jpg\",\"width\":1200,\"height\":630,\"caption\":\"Generative AI Part 13 banner: hybrid search with BM25 and vector search, RRF fusion, re-ranking and query rewriting\"},\"datePublished\":\"2026-12-01T14:38:26+00:00\",\"dateModified\":\"2026-12-01T14:38:27+00:00\",\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#webpage\"},\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#webpage\"},\"articleSection\":\"AI, BM25, Hybrid Search, Python, Query Rewriting, RAG, Re-ranking, Series: Generative AI\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#breadcrumblist\",\"itemListElement\":[{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"position\":2,\"name\":\"AI\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#listItem\",\"name\":\"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#listItem\",\"position\":3,\"name\":\"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting\",\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}}]},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/\",\"name\":\"Lokendra\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#authorImage\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g\",\"width\":96,\"height\":96,\"caption\":\"Lokendra\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#webpage\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/\",\"name\":\"Hybrid Search, Re-ranking & Query Rewriting for RAG\",\"description\":\"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.\",\"inLanguage\":\"en-US\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#breadcrumblist\"},\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"creator\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/genai-series-part-13-hybrid-search-reranking.jpg\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#mainImage\",\"width\":1200,\"height\":630,\"caption\":\"Generative AI Part 13 banner: hybrid search with BM25 and vector search, RRF fusion, re-ranking and query rewriting\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/12\\\/01\\\/genai-series-part-13-hybrid-search-reranking\\\/#mainImage\"},\"datePublished\":\"2026-12-01T14:38:26+00:00\",\"dateModified\":\"2026-12-01T14:38:27+00:00\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"inLanguage\":\"en-US\",\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"}}]}\n\t\t<\/script>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Hybrid Search, Re-ranking & Query Rewriting for RAG","description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.","canonical_url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/","robots":"max-image-preview:large","keywords":"","webmasterTools":{"miscellaneous":""},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"BlogPosting","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#blogposting","name":"Hybrid Search, Re-ranking & Query Rewriting for RAG","headline":"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting","author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/11\/genai-series-part-13-hybrid-search-reranking.jpg","width":1200,"height":630,"caption":"Generative AI Part 13 banner: hybrid search with BM25 and vector search, RRF fusion, re-ranking and query rewriting"},"datePublished":"2026-12-01T14:38:26+00:00","dateModified":"2026-12-01T14:38:27+00:00","inLanguage":"en-US","mainEntityOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#webpage"},"isPartOf":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#webpage"},"articleSection":"AI, BM25, Hybrid Search, Python, Query Rewriting, RAG, Re-ranking, Series: Generative AI"},{"@type":"BreadcrumbList","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","position":1,"name":"Home","item":"https:\/\/devdojo.co.in\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","position":2,"name":"AI","item":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#listItem","name":"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting"},"previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","name":"Home"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#listItem","position":3,"name":"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting","previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}}]},{"@type":"Organization","@id":"https:\/\/devdojo.co.in\/#organization","name":"DevDojo","description":"Empowering Developers","url":"https:\/\/devdojo.co.in\/"},{"@type":"Person","@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author","url":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/","name":"Lokendra","image":{"@type":"ImageObject","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#authorImage","url":"https:\/\/secure.gravatar.com\/avatar\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g","width":96,"height":96,"caption":"Lokendra"}},{"@type":"WebPage","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#webpage","url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/","name":"Hybrid Search, Re-ranking & Query Rewriting for RAG","description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.","inLanguage":"en-US","isPartOf":{"@id":"https:\/\/devdojo.co.in\/#website"},"breadcrumb":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#breadcrumblist"},"author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"creator":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/11\/genai-series-part-13-hybrid-search-reranking.jpg","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#mainImage","width":1200,"height":630,"caption":"Generative AI Part 13 banner: hybrid search with BM25 and vector search, RRF fusion, re-ranking and query rewriting"},"primaryImageOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/#mainImage"},"datePublished":"2026-12-01T14:38:26+00:00","dateModified":"2026-12-01T14:38:27+00:00"},{"@type":"WebSite","@id":"https:\/\/devdojo.co.in\/#website","url":"https:\/\/devdojo.co.in\/","name":"DevDojo","description":"Empowering Developers","inLanguage":"en-US","publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"}}]},"og:locale":"en_US","og:site_name":"DevDojo - Empowering Developers","og:type":"article","og:title":"GenAI Part 13: Hybrid Search &amp; Re-ranking for RAG","og:description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.","og:url":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/","article:published_time":"2026-12-01T14:38:26+00:00","article:modified_time":"2026-12-01T14:38:27+00:00","twitter:card":"summary_large_image","twitter:title":"GenAI Part 13: Hybrid Search &amp; Re-ranking for RAG","twitter:description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries."},"aioseo_meta_data":{"post_id":"319","title":"Hybrid Search, Re-ranking & Query Rewriting for RAG","description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.","keywords":null,"keyphrases":{"focus":{"keyphrase":"hybrid search","score":82},"additional":[]},"primary_term":null,"canonical_url":null,"og_title":"GenAI Part 13: Hybrid Search & Re-ranking for RAG","og_description":"Learn hybrid search for RAG: combine BM25 keyword search and vector search with RRF, re-rank results with a cross-encoder and rewrite vague queries.","og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":"","og_custom_url":null,"og_article_section":null,"og_article_tags":null,"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"BlogPosting","isEnabled":true},"graphs":[]},"schema_type":"default","schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":"-1","robots_max_videopreview":"-1","robots_max_imagepreview":"large","priority":0,"frequency":"default","local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":{"faqs":[],"keyPoints":[],"schemas":[],"titles":[],"descriptions":[],"socialPosts":{"email":{"subject":"","preview":"","content":""},"linkedin":[],"twitter":[],"facebook":[],"instagram":[]}},"created":"2026-11-30 13:02:39","updated":"2026-12-01 14:38:27","focus_keyword":"hybrid search","additional_keywords":null,"truseo_locale":null,"seo_analyzer_scan_date":null},"aioseo_breadcrumb":"<div class=\"aioseo-breadcrumbs\"><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/\" title=\"Home\">Home<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/index.php\/category\/ai\/\" title=\"AI\">AI<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\tGenerative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting\n\t\t<\/span><\/div>","aioseo_breadcrumb_json":[{"label":"Home","link":"https:\/\/devdojo.co.in\/"},{"label":"AI","link":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/"},{"label":"Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting","link":"https:\/\/devdojo.co.in\/index.php\/2026\/12\/01\/genai-series-part-13-hybrid-search-reranking\/"}],"_links":{"self":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/319","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/comments?post=319"}],"version-history":[{"count":1,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/319\/revisions"}],"predecessor-version":[{"id":324,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/319\/revisions\/324"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media\/318"}],"wp:attachment":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media?parent=319"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/categories?post=319"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/tags?post=319"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}