Search and Retrieval
Filtering
A filter limits a search to the passages you name: chosen books, authors or categories, one surah, or the passages on one ayah. POST /v1/search and POST /v1/search/guided take the same filter object and check it with the same code.
The filter object
Send filter in the JSON body of a search. Every field is optional. A field you leave out does not limit the search.
| Field | Type | Rules | Keeps |
|---|---|---|---|
books | number[] | At most 20 distinct ids, each a whole number above 0 | Passages from any of these books |
authors | number[] | At most 20 distinct ids, each a whole number above 0 | Passages by any of these authors |
categories | number[] | At most 20 distinct ids, each a whole number above 0 | Passages from books in any of these categories |
surah | number | A whole number from 1 to 114 | Passages the library has placed in this surah |
ayah | number | A whole number from 1 to 286. Needs surah, and must be an ayah of that surah | Passages whose ayah range includes this ayah |
quran | string | "include" (the default), "exclude" or "only". "only" cannot be combined with books, authors or categories | The Qur'an's own ayahs beside the books, left out, or alone |
As a TypeScript type:
type SearchFilter = {books?: number[]; // at most 20 idsauthors?: number[]; // at most 20 idscategories?: number[]; // at most 20 idssurah?: number; // 1 to 114ayah?: number; // needs surahquran?: "include" | "exclude" | "only";};
How a filter is read
- Fields are combined with AND. The ids in one list are combined with OR:
"books": [1503, 41]keeps passages from either book, and adding"surah": 2keeps only those of them placed in surah 2. - A missing field, a field set to
nulland an empty list all mean no limit on that field."filter": {},"filter": nulland nofilterat all search the whole library. - A list is a set. An id given twice counts once, and order does not matter:
[1503, 41, 41]is the same filter as[41, 1503]. The limit of 20 counts distinct ids. - Ids start at 1. The Qur'an is book 0, in category 0, and cannot be put in a list. Use
quranfor it. - Unknown fields are refused. A misspelt field such as
bookfails with a 400 instead of quietly searching everything. - Before it keys its cache of answers, the service sorts each list and leaves out
quranwhen it is"include", or"exclude"beside a list, so two filters that mean the same thing share a cache entry.
Why 20: keyword search binds every id as a parameter of one SQL statement (two for each book, the ends of its range of passage ids). With 20 per list a statement binds at most 85 values, under D1's limit of 100 bound parameters per query.
What surah and ayah match
When a book is loaded, the library places each passage on the ayahs it explains. That place is the passage's ayahs field: { "surah", "from", "to" }.
surahkeeps passages placed in that surah.ayahkeeps passages whose range includes it:fromis at or before the ayah andtois at or after it. For example, a passage placed on ayahs 254 to 257 matches"ayah": 255.- A passage under a surah's heading but before its first ayah has a surah and no ayah range. It matches
surahalone, notayah, and itsayahsfield isnull. - A passage the library could not place has no surah, so any
surahorayahfilter leaves it out. - The filter uses a passage's own place, not the ayahs it quotes in ﴿…﴾ (those are its
quotesfield). To list the passages that quote an ayah, useGET /v1/quotes/:surah/:ayah. - Search uses every book's placement, whatever the book's
ayahReady. The ayah lookup,GET /v1/tafsir/:surah/:ayah, answers only from books whoseayahReadyis true.
The Qur'an in a filter
The Qur'an is in the library as book 0: one passage per ayah, in Tanzil's text, with kind "ayah" and no author. quran decides whether its ayahs are searched.
| Value | Effect |
|---|---|
"include" | The default. The Qur'an's ayahs are searched beside the scholars' passages. |
"exclude" | Only the scholars' passages are searched. |
"only" | Only the Qur'an's ayahs are searched. |
- A list of books, authors or categories already leaves the Qur'an out, because no list can hold id 0.
"exclude"beside a list changes nothing. "only"beside a list could match nothing, so the request is refused with a 400.surahandayahapply to the Qur'an's ayahs too: each is placed on its own surah and ayah. With the default"include", a search filtered to one ayah can return that ayah itself beside the passages on it. Add"quran": "exclude"to keep the scholars' passages alone.
Examples
The API is live at https://grep.getbayan.app. A search body is JSON, sent with Content-Type: application/json. Each passage in results carries book.id, author.id (author is null for the Qur'an's ayahs) and ayahs, so you can see why it matched.
One surah
Search surah 2 (al-Baqarah) only.
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الصبر", "filter": {"surah": 2}}'
const response = await fetch("https://grep.getbayan.app/v1/search", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ query: "الصبر", filter: { surah: 2 } }),});const answer = await response.json();if (!response.ok) throw new Error(answer.error.message);for (const passage of answer.results) console.log(passage.citation.text);
import requests response = requests.post("https://grep.getbayan.app/v1/search",json={"query": "الصبر", "filter": {"surah": 2}},)response.raise_for_status()for passage in response.json()["results"]:print(passage["citation"]["text"])
One ayah
Search the passages on 2:255 only. ayah always goes with surah.
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الكرسي", "filter": {"surah": 2, "ayah": 255, "quran": "exclude"}}'
const response = await fetch("https://grep.getbayan.app/v1/search", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({query: "الكرسي",filter: { surah: 2, ayah: 255, quran: "exclude" },}),});
response = requests.post("https://grep.getbayan.app/v1/search",json={"query": "الكرسي","filter": {"surah": 2, "ayah": 255, "quran": "exclude"},},)
"quran": "exclude" keeps the ayah itself out of the results. To read the passages on an ayah without a query, use the ayah lookup, GET /v1/tafsir/2/255, instead of a search. It answers a page of the default tafsirs, or of the books named in ?books=, from books whose ayahReady is true.
A set of books
Search three tafsirs only:
| Book id | Name | Author id | Author |
|---|---|---|---|
1503 | تفسير ابن كثير - ط ابن الجوزي | 3 | ابن كثير |
41 | تفسير البغوي - طيبة | 4 | البغوي، أبو محمد |
42 | تفسير السعدي = تيسير الكريم الرحمن | 128 | عبد الرحمن السعدي |
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الصبر عند المصيبة", "filter": {"books": [1503, 41, 42]}}'
const response = await fetch("https://grep.getbayan.app/v1/search", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({query: "الصبر عند المصيبة",filter: { books: [1503, 41, 42] },}),});
response = requests.post("https://grep.getbayan.app/v1/search",json={"query": "الصبر عند المصيبة", "filter": {"books": [1503, 41, 42]}},)
Combining fields
Two books, on one ayah. Every field must hold for a passage to be kept.
{"query": "الكرسي","filter": { "books": [1503, 41], "surah": 2, "ayah": 255 }}
By author instead of by book. Author 3 is ابن كثير; the filter keeps every book of his in the library.
{"query": "الصبر","filter": { "authors": [3], "surah": 3 }}
The Qur'an alone
Search the Qur'an's ayahs and nothing else, here within surah 2.
{"query": "الصبر","filter": { "quran": "only", "surah": 2 }}
Filters in guided search
POST /v1/search/guided takes { query, topK?, filter? }. Its query and filter are checked by the same parser as /v1/search, with the same rules and the same messages. Every search a guided search runs uses the filter: the person's own words in the first round, and each query the model writes.
curl -X POST https://grep.getbayan.app/v1/search/guided \-H "Content-Type: application/json" \-d '{"query": "الصبر عند المصيبة", "topK": 10, "filter": {"books": [1503, 41, 42]}}'
Finding ids
Book, author and category ids come from the book list. There is no separate list of authors or categories: each book carries its author's id and its category's id.
| Call | Answers |
|---|---|
GET /v1/books | { "books": Book[] }: every book except the Qur'an, ordered by id |
GET /v1/books?cat=3 | The books of one category. cat is the only parameter; ?cat=0 lists the Qur'an |
GET /v1/books/:id | { "book": Book }, or 404 not_found. GET /v1/books/0 is the Qur'an, with Tanzil's credit and copyright block |
| Filter field | Take the id from |
|---|---|
books | book.id |
authors | book.author.id (author is null for the Qur'an) |
categories | book.category.id |
curl -s https://grep.getbayan.app/v1/books \| jq '.books[] | {id, name, author: .author.id, category: .category.id}'
const response = await fetch("https://grep.getbayan.app/v1/books");const { books } = await response.json();// The ids of the books by one author: author 3 is Ibn Kathir.const ids = books.filter((book) => book.author?.id === 3).map((book) => book.id);
books = requests.get("https://grep.getbayan.app/v1/books").json()["books"]for book in books:print(book["id"], book["author"]["id"], book["category"]["id"], book["name"])
One book:
curl -s https://grep.getbayan.app/v1/books/42{"book": {"id": 42,"name": "تفسير السعدي = تيسير الكريم الرحمن","edition": "الكتاب: تيسير الكريم الرحمن في تفسير كلام المنان\nالمؤلف: عبد الرحمن بن ناصر بن عبد الله السعدي (ت ١٣٧٦هـ)\nالمحقق: عبد الرحمن بن معلا اللويحق\nالناشر: مؤسسة الرسالة\nالطبعة: الأولى ١٤٢٠هـ -٢٠٠٠ م\nعدد الأجزاء: ١\n[ترقيم الكتاب موافق للمطبوع]","author": {"id": 128,"name": "عبد الرحمن السعدي","died": 1376},"category": {"id": 3,"name": "التفسير"},"passages": 4028,"ayahReady": true,"printed": true,"pdf": true,"reader": "https://app.turath.io/book/42","attribution": null,"notice": null}}
The book answers are the same for every caller and carry Cache-Control: public, max-age=3600, s-maxage=86400, so an app can keep the list for an hour instead of fetching it before each search.
Book fields
| Field | Type | Meaning |
|---|---|---|
id | number | turath's book id; 0 for the Qur'an. Use it in filter.books |
name | string | turath's name for the book; القرآن الكريم for the Qur'an |
edition | string | null | turath's edition line: the title, author, editor, publisher and printing. For the Qur'an, the Tanzil text's title and Tanzil's credit |
author | object | null | { id, name, died, diedLabel? }. id goes in filter.authors. died is the Hijri year of death, or null. diedLabel is there only when turath marks the year as not exact: نحو, بعد or ق. null for the Qur'an |
category | object | { id, name }. id goes in filter.categories |
passages | number | How many passages the book was cut into |
ayahReady | boolean | Whether the ayah lookup answers from this book |
printed | boolean | null | true when the page numbers are the printed edition's, false when turath numbers the book another way, null when turath does not say |
pdf | boolean | Whether turath has a scan of the printed book that Bayan can link to |
reader | string | Where to read the whole book: turath's reader, or Quran.com for the Qur'an |
attribution | string | null | For the Qur'an: Tanzil's credit, link and license. null for every other book |
notice | string | null | For the Qur'an: Tanzil's copyright block, verbatim. null for every other book |
In its first phase, now loaded, the library's books are the 275 tafsirs in turath's category 3 (التفسير). The Qur'an alone is in category 0.
How filters apply
A hybrid search runs keyword search and meaning search side by side and merges their lists. "mode": "keyword" or "mode": "semantic" runs one of them. The filter goes into each search's own query, so each returns its best passages among those the filter keeps. Nothing is filtered after the search.
| Field | Keyword search (D1, FTS5) | Meaning search (Vectorize) |
|---|---|---|
books | A range of passage ids per book, the ranges joined with OR: f.rowid >= ? AND f.rowid < ?. No join | book_id: { $in: [...] } |
authors | b.author_id IN (...), joining each passage to its book | author_id: { $in: [...] } |
categories | b.cat_id IN (...), joining each passage to its book | cat_id: { $in: [...] } |
surah | c.surah = ?, joining the passage table | surah: n |
ayah | c.ayah_from <= ? AND c.ayah_to >= ? | ayah_from: { $lte: n }, ayah_to: { $gte: n } |
quran: "only" | f.rowid < ?, bound to 1,000,000. No join | cat_id: { $eq: 0 } |
quran: "exclude" | f.rowid >= ?, bound to 1,000,000. No join | cat_id: { $ne: 0 } |
In keyword search
- A passage's id is its book's id × 1,000,000 plus its position in the book. Book 1503's passages are the ids from 1,503,000,000 up to, not including, 1,504,000,000, so a book filter is a range on the full-text index itself and needs no join. The Qur'an is book 0: its ayahs are the ids below 1,000,000.
authorsandcategoriesjoin each passage to its book.surahandayahjoin the passage table, where each passage's place is kept. The join is written so that the full-text index stays the outer loop: the filter narrows the matches, never the other way round.- Keyword search runs in up to three tiers: the query as a phrase, every word, then any word, the last only when the first two find fewer than ten passages. Each tier carries the same conditions. When the query has four or more words besides stopwords, the any-word tier keeps the three rarest, found by counting each word in the whole library, unfiltered; the search itself is filtered.
- A query with no Arabic letter skips keyword search, which holds Arabic only, unless the service turns it into Arabic keyword queries. That needs the model guided search uses, so it is off as configured. When it runs, each of those queries is searched with the same filter.
In meaning search
Each passage's vector in Vectorize carries book_id, cat_id and author_id; surah when the passage is placed in a surah; and ayah_from and ayah_to when it has an ayah range. The filter becomes a Vectorize metadata filter whose fields are combined with AND. For { "books": [1503, 41], "surah": 2, "ayah": 255 } the service sends:
{"book_id": { "$in": [41, 1503] },"surah": 2,"ayah_from": { "$lte": 255 },"ayah_to": { "$gte": 255 }}
The Qur'an is the only book in category 0, so quran becomes a rule on cat_id. When a categories list is given, that list is the one rule on cat_id, and it already leaves the Qur'an out.
After the merge
- The merged list, the reranker and
topKsee only passages the filter kept.minScorecan still drop some of them. - The answer's
ayahslists the results' own ayahs and the ayahs they quote. With asurahfilter it can therefore name ayahs of other surahs, quoted by passages in the surah you asked for.
Errors
A filter that breaks a rule is refused with 400 invalid_request and a message that names the field. A request is refused for its first mistake. In /v1/search unknown fields of the body are checked first, then query, topK, rerank and rerankLimit, then the filter; within the filter, unknown fields come first, then the fields in the order of the table above.
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الكرسي", "filter": {"ayah": 255}}'
{"error": {"code": "invalid_request","message": "filter.ayah needs filter.surah."}}
| Filter sent | Message |
|---|---|
"filter": [1503] | filter must be an object. |
{ "book": [1503] } | Unknown field filter.book. Allowed: filter.books, filter.authors, filter.categories, filter.surah, filter.ayah, filter.quran. |
{ "books": 1503 }, { "books": [0] }, { "books": [1503, "41"] }, or 21 distinct ids | filter.books must be a list of at most 20 ids (whole numbers above 0). The same for filter.authors and filter.categories |
{ "surah": 115 }, { "surah": "2" } | filter.surah must be a whole number from 1 to 114. |
{ "surah": 2, "ayah": 287 } | filter.ayah must be a whole number from 1 to 286. |
{ "ayah": 255 } | filter.ayah needs filter.surah. |
{ "surah": 1, "ayah": 8 } | Surah 1 has no ayah 8. |
{ "quran": "all" } | filter.quran must be one of include, exclude, only. |
{ "quran": "only", "books": [1503] } | filter.quran "only" cannot be combined with filter.books, filter.authors or filter.categories: the Qur'an is in none of them. |
The book calls refuse mistakes the same way: GET /v1/books?book=1 answers Unknown parameter. Allowed: cat., and an id that is not a whole number from 0, as in GET /v1/books/abc, answers id must be an id: a whole number from 0. A well-formed id with no book answers 404 not_found: There is no book with this id.