Search and Retrieval
Ranking
A search runs keyword search and meaning search side by side, merges their two lists by rank, and, when the service has a reranker, has a cross-encoder rerank the best of the merge. As configured it has none, so the merged order is the answer. This page describes each step as the service runs it, with the numbers it uses.
Ranking only decides the order of what is found: the scholars' passages and, unless the filter leaves them out, the Qur'an's ayahs. A reranker, when one is set, reads the query beside each passage and answers a number. No model writes anything that is shown.
The order of operations
For a request to POST /v1/search in the default hybrid mode:
- Search two ways at once. Keyword search (SQLite FTS5) and meaning search (embeddings in Cloudflare Vectorize) each return a ranked list of up to 50 passage ids, or up to
topKwhentopKis above 50. Keyword search runs only when the query has an Arabic letter, or when the service has turned the query into Arabic search terms. Each path has its own timeout: 4 seconds for keywords, 6 seconds for meaning. If one path fails, the search carries on with the other. If every path tried fails, the answer is503 search_unavailable. - Fuse. The lists are merged by reciprocal rank fusion with
k = 60. The bestmax(30, topK)passages are kept, at most 100. - Read the texts. The kept passages are read from the database in one query. A passage that is no longer in the library is skipped.
- Rerank. When
rerankis true and the service has a reranker, the bestmax(30, rerankLimit)passages are scored against the query, and the bestrerankLimitare kept. The reranker is waited for 3 seconds. If it fails, the bestrerankLimitin the merged order are kept instead. - Or cut. When
rerankis false, or the service has no reranker, the merged order is cut totopK. - Apply
minScore, when it is set and a 0–1 score applies to the results (see minScore).
In semantic mode only meaning search runs, and in keyword mode only keyword search. The other steps are the same.
Parameters
These fields of the search request decide the order and the number of results.
| Field | Type | Default | Effect on ranking |
|---|---|---|---|
query | text, 1–300 characters after trimming | required | Keyword search reads its words in the search form. Meaning search embeds it. The reranker reads it as sent, with harakat stripped. |
mode | "hybrid", "semantic" or "keyword" | "hybrid" | Which lists are fused: both, meaning search only, or keyword search only. In keyword mode a query with no Arabic letter finds nothing, unless the service translates it. |
topK | whole number, 1–100 | 10 | Results answered when not reranked. Also sets how many merged passages are kept, max(30, topK), and how deep each path searches when it is above 50. |
rerank | boolean | true | Rerank the merged passages, when the service has a reranker. |
rerankLimit | whole number, 1–100, at most topK | topK | Results answered after reranking, and after a failed rerank. The reranker reads max(30, rerankLimit) passages. |
minScore | number, 0–1 | none | Drops results below a 0–1 score. Which score depends on whether the results were reranked and on the mode. |
A request cannot choose the reranker, the fusion constant or the weights: they are settings of the service. A field the service does not know, such as rerankModel, is refused with 400 invalid_request. filter decides which passages each path may return; it is applied inside both searches, before anything is ranked.
How many passages each step handles
| Step | Passages, at most | Default request (topK 10) |
|---|---|---|
| Each path returns | 50, or topK when it is above 50 | 50 |
| Kept after fusion | max(30, topK), at most 100 | 30 |
| Read by the reranker | max(30, rerankLimit) of those kept | 30 |
| Answered, reranked or after a failed rerank | rerankLimit | 10 |
| Answered, not reranked | topK | 10 |
After minScore | those that pass, never more | 10 or fewer |
Two more cases, as upper bounds: with topK 20 and rerankLimit 5, each path returns 50, 30 are kept, the reranker reads 30, and 5 are answered. With topK 80 and rerankLimit 60, each path returns 80, 80 are kept, the reranker reads 60, and 60 are answered.
Keyword ranking
Every passage is indexed in two FTS5 columns. The norm column holds its search form: harakat removed, أ إ آ written ا, ى written ي, ؤ written و, ئ written ي, and ة written ه. The stem column holds each word's light stem: the word without prefixes such as و and ال and without a common ending. These forms are only used for search. The text you are answered is the passage as published.
From query to match
- The query is split into words, in the search form.
- Stopwords are dropped from the word tiers: a list of 181 Arabic function words, such as من, في, عن and قال. A query made only of stopwords still searches for those words.
- Each word is used once, and at most 12 words are kept.
- Each word becomes
(norm:"word" OR stem:"stem"): the word as written, or any word with the same stem.
Three tiers
Keyword search asks three questions, best first.
| Tier | Matches | Runs |
|---|---|---|
| Phrase | The query's first 12 words in a row, in the norm column. Stopwords and repeated words are kept. | When the query has two or more words. |
| Every word | Passages with every kept word (AND). | Always. |
| Rarest words | Passages with any of at most 3 kept words, the rarest (OR). | Only when the first two tiers together find fewer than 10 passages, and the query has two or more kept words. |
The phrase and every-word tiers are sent in one round trip. The keyword list is the phrase hits, then the every-word hits, then the rarest-word hits, each passage once, cut to the path's depth. So in the keyword list a phrase hit always ranks above a passage that only has every word.
How the rarest words are chosen: with 3 kept words or fewer, all of them are used. With 4 or more, one statement first counts how many passages hold each word, over the whole library and without the filter, counting at most 5,000 per word. Words found nowhere are left out. The 3 with the fewest passages are joined with OR; words that tie keep the query's order. This bounds the cost of the tier: an OR of many common words would match most of the library.
bm25 weights
Within each tier, passages are ordered by FTS5's bm25, best match first, with a weight per column: ORDER BY bm25(chunks_fts, 2.0, 1.0).
The first weight is for norm, the second for stem. A match on the word as written counts twice as much as a match on its stem. A passage with the query's own words matches in both columns, so it tends to rank above one that only shares their stems. It is a tendency, not a rule: bm25 also weighs how often each word occurs, how rare it is and how long the passage is. The bm25 values are not part of the answer. Only the order of the keyword list goes into the fusion.
Example
For the query الصبر عند المصيبة, the service builds these expressions. عند is a stopword: it stays in the phrase and leaves the word tiers. المصيبة is written المصيبه in the search form.
| Tier | MATCH expression |
|---|---|
| Phrase | norm:"الصبر عند المصيبه" |
| Every word | (norm:"الصبر" OR stem:"صبر") AND (norm:"المصيبه" OR stem:"مصيب") |
| Rarest words | (norm:"الصبر" OR stem:"صبر") OR (norm:"المصيبه" OR stem:"مصيب") |
The query has two kept words, so the third tier uses both, and runs only if the first two find fewer than 10 passages.
Meaning ranking
The query, with harakat stripped, is embedded by the service's embedder (@cf/google/embeddinggemma-2 on Workers AI, at 256 dimensions). Vectorize returns the nearest passages by cosine similarity, nearest first. That order is the meaning list. The query's embedding is kept for a day in the cache of the data centre that answered, so a query repeated there within the day is not embedded again.
Each match also has a vector score: the cosine similarity mapped to 0–1 as (1 + similarity) / 2. It is used only for minScore in semantic mode without reranking. It is not in the answer.
Reciprocal rank fusion
bm25 values and cosine similarities are on different scales, so the two lists are merged by rank alone. A passage's fused score is the sum, over the lists it is in, of:
score += weight / (k + rank) // rank counted from 1, k = 60, weight = 1kis 60 for every request, so the same lists merge the same way whatevertopKwas asked. A smallkover-rewards the top of one list: withk = 10, the first passage of one list (1/11) would outrank a passage ranked 13th by both (2/23). Withk = 60the passage found by both wins (2/73 against 1/61).- Both lists weigh 1.
- A passage counts once per list, at its best rank.
- Ties keep the order passages were first met. The meaning list is read first, so when a passage meaning search found ties with one only keyword search found, meaning search's comes first.
- Translated queries share one weight. When the service turns a query with no Arabic letter into Arabic keyword queries (up to 3), each gives its own keyword list, and each of the n lists weighs
1 / n. Together they count as much as the one keyword list of an Arabic query. This happens only when the service has a model set for it (itsGUIDED_MODELsetting) and the request does not send"translate": false.
The fused score is the score of each result.
Worked example
Say meaning search ranks passages A, B, C, and keyword search ranks C, A, D.
| Passage | Meaning rank | Keyword rank | Fused score |
|---|---|---|---|
| A | 1 | 2 | 1/61 + 1/62 = 0.032522… |
| C | 3 | 1 | 1/63 + 1/61 = 0.032266… |
| B | 2 | none | 1/62 = 0.016129… |
| D | none | 3 | 1/63 = 0.015873… |
The merged order is A, C, B, D. B is second for meaning search, but C, which both paths found, passes it.
What this means for score: from one list it is at most 1/61 (0.01639…), from two at most 2/61 (0.03278…). In keyword or semantic mode, with one list (a query that was not translated), the passage its path ranked nth scores exactly 1 / (60 + n).
Reranking
A reranker is a cross-encoder: it reads the query and a passage together and scores how well the passage answers the query. It is slower than the two search paths, so it reads only the best of the merge.
What it reads
- The best
max(30, rerankLimit)merged passages. - Each passage's text with harakat stripped, cut to 1,500 characters.
- The query as sent, with harakat stripped. When a query was translated, the reranker still reads the query as sent, never the Arabic terms.
The service asks for the best rerankLimit and checks the answer. An answer that is not a list of numeric scores counts as a failed rerank. Within the list, a score for a passage it was not given, a repeated one, or one that is not a finite number is ignored, and if no score is left the rerank has failed. The results are sorted by score, highest first, and each carries its rerankScore.
Rerankers
The service is set up with one reranker, or none, by its RERANKER setting. It is "none": in the service's model test, bge-reranker-base lowered the quality of results with every embedder, Arabic and English queries alike.
RERANKER | Model | Notes |
|---|---|---|
"workers-ai" | @cf/baai/bge-reranker-base on Workers AI | Sent { query, contexts: [{ text }], top_k }. Cloudflare's model page says the model's score can be mapped to 0–1 with a sigmoid, but not whether the score Workers AI answers has been mapped already. When any score in an answer is outside 0–1, every score in that answer is passed through a sigmoid. The order is kept, and rerankScore stays between 0 and 1. |
"cohere" | rerank-v5.0-fast, at POST https://api.cohere.com/v2/rerank | Sent { documents, query, top_n, model }. Each result's relevance_score becomes its rerankScore. Needs the COHERE_API_KEY secret. Without it, searches are not reranked. |
"none" (the current setting) | none | Searches are not reranked: results come in the merged order, cut to topK. |
Any other value is a mistake in the service's configuration: every search with rerank on and results to rerank answers 500 internal, rather than going out unreranked without notice.
Timeout and fallback
- The reranker is waited for 3 seconds. Then its request is aborted.
- If it times out, fails, or answers no usable score, the search still answers
200, with the bestrerankLimitpassages in the merged order and norerankScore. A merged order is better than no answer. - The answer does not say that reranking failed. The missing
rerankScoreis the sign. - An answer with a failed path, a failed translation or a failed rerank is not kept in the service's cache, so the same request tries again. A complete answer is kept for an hour.
minScore
minScore drops results whose score is below it. A fused score is never more than 2/61, and a bm25 value has no fixed range: neither is on a 0–1 scale. So minScore is held only to a 0–1 score, and to one score at a time:
| Results | Kept when |
|---|---|
| Reranked, in any mode | rerankScore >= minScore |
semantic mode, not reranked | the vector score, (1 + similarity) / 2, is >= minScore |
hybrid or keyword mode, not reranked | always: minScore is not applied |
"Not reranked" means rerank was false, the service has no reranker (RERANKER is "none", or "cohere" without its key), or the rerank failed.
- It is applied last, after the cut to
rerankLimitortopK. It removes results and never brings others up to take their place, so an answer can hold fewer results than asked for, or none. - The comparison is
>=: a result exactly atminScoreis kept. - In semantic mode without reranking, the score held to
minScoreis not in the answer.scoreis still the fused score. - The rule follows the mode you ask for. A
hybridsearch for a query with no Arabic letter that is not translated runs meaning search alone, but unless it is reranked,minScoreis not applied to it. Ask forsemanticmode to have the vector score held tominScore.
Scores in the response
Every passage in results has score. It has rerankScore only when the reranker ran and answered.
| Field | Present | Meaning |
|---|---|---|
score | Every search result | The fused score from reciprocal rank fusion. Higher is better. At most 1/61 from one list and 2/61 from two. It depends only on ranks, so compare it within one answer. |
rerankScore | Only when the results were reranked | The reranker's score, 0–1, higher is better. |
When the results were reranked they are in rerankScore order, so score need not fall down the list. Otherwise they are in score order. rerankScore is absent when rerank was false, when the service has no reranker, and when the rerank failed or timed out.
Examples
A hybrid search, reranked
topK is 20 and rerankLimit 5: the five best after reranking come back.
curl -s https://grep.getbayan.app/v1/search \-H 'Content-Type: application/json' \--data-binary @- <<'EOF'{"query": "الصبر عند المصيبة", "topK": 20, "rerankLimit": 5}EOF
const response = await fetch("https://grep.getbayan.app/v1/search", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ query: "الصبر عند المصيبة", topK: 20, rerankLimit: 5 }),});const { results } = await response.json();for (const passage of results) {// rerankScore is missing when nothing was reranked: then the order is the merged one.console.log(passage.id, passage.score, passage.rerankScore ?? "not reranked");}
import requests response = requests.post("https://grep.getbayan.app/v1/search",json={"query": "الصبر عند المصيبة", "topK": 20, "rerankLimit": 5},timeout=30,)for passage in response.json()["results"]:# rerankScore is missing when nothing was reranked: then the order is the merged one.print(passage["id"], passage["score"], passage.get("rerankScore", "not reranked"))
Each path returns up to 50 ids, up to 30 merged passages are kept, the reranker reads all of them, and the five it scores highest are answered, each with score and rerankScore. If the reranker fails, the answer is the first five of the merged order, without rerankScore. As the service is configured, with no reranker, this request is answered with the first 20 of the merged order, none with a rerankScore.
Keyword mode, not reranked
With mode "keyword" and rerank false, the order is the keyword list itself and every score follows from its rank.
curl -s https://grep.getbayan.app/v1/search \-H 'Content-Type: application/json' \--data-binary @- <<'EOF'{"query": "الصبر عند المصيبة", "mode": "keyword", "rerank": false, "topK": 3}EOF
The answer below is the live API's, over all 275 tafsirs and the Qur'an, on 28 November 2026. When books are loaded again its passages can change. The scores will not: in this mode, the first three results score 1/61, 1/62 and 1/63. Each passage is cut here to its id and score. The full answer also carries, among other fields, each passage's book, author, place, text, citation and source, and the ayahs summary.
{"query": "الصبر عند المصيبة","language": "ar","translated": false,"results": [{ "id": "639017440", "score": 0.01639344262295082 },{ "id": "12851001283", "score": 0.016129032258064516 },{ "id": "22593004746", "score": 0.015873015873015872 }]}
A passage id is the book id × 1,000,000 + the passage's position, so these are from books 639, 12851 and 22593. There is no rerankScore, because nothing was reranked. A minScore would not be applied here, because keyword mode without reranking has no 0–1 score.
A floor on the rerank score
curl -s https://grep.getbayan.app/v1/search \-H 'Content-Type: application/json' \--data-binary @- <<'EOF'{"query": "الصبر عند المصيبة", "topK": 10, "minScore": 0.5}EOF
The value 0.5 is only an example. The ten reranked results are kept only where rerankScore is at least 0.5, so fewer than ten may come back. If the rerank fails, the results have no 0–1 score in hybrid mode, and all ten are answered in the merged order. That is also what this request gets while the service has no reranker, as now.
Errors
Mistakes in these fields are refused with 400 invalid_request, for the first mistake found:
| Request | message |
|---|---|
"topK": 10, "rerankLimit": 20 | rerankLimit cannot be larger than topK |
"topK": 0 | topK must be a whole number from 1 to 100. |
"minScore": 2 | minScore must be a number from 0 to 1. |
"rerank": "yes" | rerank must be true or false. |
"rerankModel": "cohere" | Unknown field rerankModel. Allowed: query, mode, topK, rerank, rerankLimit, minScore, filter, translate. |
{"error": {"code": "invalid_request","message": "rerankLimit cannot be larger than topK"}}