Skip to content

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.

FieldTypeRulesKeeps
booksnumber[]At most 20 distinct ids, each a whole number above 0Passages from any of these books
authorsnumber[]At most 20 distinct ids, each a whole number above 0Passages by any of these authors
categoriesnumber[]At most 20 distinct ids, each a whole number above 0Passages from books in any of these categories
surahnumberA whole number from 1 to 114Passages the library has placed in this surah
ayahnumberA whole number from 1 to 286. Needs surah, and must be an ayah of that surahPassages whose ayah range includes this ayah
quranstring"include" (the default), "exclude" or "only". "only" cannot be combined with books, authors or categoriesThe Qur'an's own ayahs beside the books, left out, or alone

As a TypeScript type:

TypeScript
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": 2 keeps only those of them placed in surah 2.
  • A missing field, a field set to null and an empty list all mean no limit on that field. "filter": {}, "filter": null and no filter at 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 quran for it.
  • Unknown fields are refused. A misspelt field such as book fails with a 400 instead of quietly searching everything.
  • Before it keys its cache of answers, the service sorts each list and leaves out quran when 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" }.

  • surah keeps passages placed in that surah.
  • ayah keeps passages whose range includes it: from is at or before the ayah and to is 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 surah alone, not ayah, and its ayahs field is null.
  • A passage the library could not place has no surah, so any surah or ayah filter leaves it out.
  • The filter uses a passage's own place, not the ayahs it quotes in ﴿…﴾ (those are its quotes field). To list the passages that quote an ayah, use GET /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 whose ayahReady is 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.

ValueEffect
"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.
  • surah and ayah apply 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
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الصبر", "filter": {"surah": 2}}'

One ayah

Search the passages on 2:255 only. ayah always goes with surah.

curl
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"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 idNameAuthor idAuthor
1503تفسير ابن كثير - ط ابن الجوزي3ابن كثير
41تفسير البغوي - طيبة4البغوي، أبو محمد
42تفسير السعدي = تيسير الكريم الرحمن128عبد الرحمن السعدي
curl
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الصبر عند المصيبة", "filter": {"books": [1503, 41, 42]}}'

Combining fields

Two books, on one ayah. Every field must hold for a passage to be kept.

Request body
{"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.

Request body
{"query": "الصبر","filter": { "authors": [3], "surah": 3 }}

The Qur'an alone

Search the Qur'an's ayahs and nothing else, here within surah 2.

Request body
{"query": "الصبر","filter": { "quran": "only", "surah": 2 }}

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
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.

CallAnswers
GET /v1/books{ "books": Book[] }: every book except the Qur'an, ordered by id
GET /v1/books?cat=3The 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 fieldTake the id from
booksbook.id
authorsbook.author.id (author is null for the Qur'an)
categoriesbook.category.id
curl
curl -s https://grep.getbayan.app/v1/books \| jq '.books[] | {id, name, author: .author.id, category: .category.id}'

One book:

curl
curl -s https://grep.getbayan.app/v1/books/42
Response
{"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

FieldTypeMeaning
idnumberturath's book id; 0 for the Qur'an. Use it in filter.books
namestringturath's name for the book; القرآن الكريم for the Qur'an
editionstring | nullturath's edition line: the title, author, editor, publisher and printing. For the Qur'an, the Tanzil text's title and Tanzil's credit
authorobject | 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
categoryobject{ id, name }. id goes in filter.categories
passagesnumberHow many passages the book was cut into
ayahReadybooleanWhether the ayah lookup answers from this book
printedboolean | nulltrue when the page numbers are the printed edition's, false when turath numbers the book another way, null when turath does not say
pdfbooleanWhether turath has a scan of the printed book that Bayan can link to
readerstringWhere to read the whole book: turath's reader, or Quran.com for the Qur'an
attributionstring | nullFor the Qur'an: Tanzil's credit, link and license. null for every other book
noticestring | nullFor 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.

FieldKeyword search (D1, FTS5)Meaning search (Vectorize)
booksA range of passage ids per book, the ranges joined with OR: f.rowid >= ? AND f.rowid < ?. No joinbook_id: { $in: [...] }
authorsb.author_id IN (...), joining each passage to its bookauthor_id: { $in: [...] }
categoriesb.cat_id IN (...), joining each passage to its bookcat_id: { $in: [...] }
surahc.surah = ?, joining the passage tablesurah: n
ayahc.ayah_from <= ? AND c.ayah_to >= ?ayah_from: { $lte: n }, ayah_to: { $gte: n }
quran: "only"f.rowid < ?, bound to 1,000,000. No joincat_id: { $eq: 0 }
quran: "exclude"f.rowid >= ?, bound to 1,000,000. No joincat_id: { $ne: 0 }
  • 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.
  • authors and categories join each passage to its book. surah and ayah join 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.

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:

Vectorize filter
{"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 topK see only passages the filter kept. minScore can still drop some of them.
  • The answer's ayahs lists the results' own ayahs and the ayahs they quote. With a surah filter 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
curl -X POST https://grep.getbayan.app/v1/search \-H "Content-Type: application/json" \-d '{"query": "الكرسي", "filter": {"ayah": 255}}'
Response
{"error": {"code": "invalid_request","message": "filter.ayah needs filter.surah."}}
Filter sentMessage
"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 idsfilter.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.