Search / Search
Search
The Search engine finds documents by their words in any language, forgiving
typos, by the vectors your embedding model makes, or by both. An index keeps
its own documents in search.db, or follows a table of an application's
database and changes in the same commit as its rows. Searches are exact by
default.
const articles = store.index<Article>('articles', { fields: { title: 2, body: 1 }, filters: ['authorId'] })
await articles.set('a-17', { title: 'Как испечь хлеб', body: '…', authorId: 42 })
const { hits, corrected } = await articles.search({ text: 'хлеба', where: { authorId: 42 } })articles = store.index("articles", Article, fields={"title": 2, "body": 1}, filters=["author_id"])
await articles.set("a-17", Article(title="Как испечь хлеб", body="…", author_id=42))
result = await articles.search(text="хлеба", where={"author_id": 42})What it guarantees
- A search by words answers what scoring every document would, by BM25, never an estimate (contract SRCH-01).
- A search by a vector answers the exact best by cosine, unless the index
asked for
recall(contract SRCH-02). - A filter keeps to the documents it passes before ranking (contract SRCH-03).
- A document set is found by the next search; a deleted one never again (contract SRCH-04).
- A table's index changes in the commit that changes the row. The one
exception is a row SQLite removes itself for a
replaceon a unique column other than the key: it leaves the index when a search next meets it, and that search never returns it (contract SRCH-07). - A misspelt word is read as its nearest, and
correctedsays so; a word that matches is never changed (contract SRCH-09). - A
totalis exact up to 10,000, and past it says "at least 10,000", never an estimate (contract SRCH-18).
Changing an index
Change an index by opening it with other options under the same name, and never version its name. A weight or the layouts change at once; a field or a filter added is read beside the index, which answers as before until the new one switches in (Rebuilds), and so is a table's index's new table or key. Only what the store cannot make again needs another name: the vectors of a new model.
Listing what it holds
An index finds; it does not list. A search with no words and no vector, a
where alone included, finds nothing, an empty page rather than every
document, and no call walks an index's documents. An album that shows its
photos newest first and finds them by their words keeps them in a table,
which SQL lists, and the table's index follows it:
const photos = db.table<Photo>('photos')
const found = db.searchIndex<Photo>('photos_search', { table: 'photos', fields: { title: 2, caption: 1 } })
const page = await photos.orderBy('taken_at', 'desc').limit(50).all() // the album, listed
const { hits } = await found.search({ text: 'море' }) // the same rows, found by their wordsphotos = db.table("photos", Photo)
found = db.search_index("photos_search", Photo, table="photos", fields={"title": 2, "caption": 1})
page = await photos.order_by("taken_at", "desc").limit(50).all()
result = await found.search("море")photos := sqldb.OpenTable[Photo](db, "photos")
found, err := search.OpenIndex[Photo](db, "photos_search", search.Table("photos"), search.Fields{"title": 2, "caption": 1})
page, err := photos.OrderBy("taken_at", sqldb.Desc).Limit(50).All(ctx)
result, err := found.Search(ctx, "море")let photos = db.table::<Photo>("photos");
let found = db.search_index::<Photo>("photos_search").table("photos").field("title", 2.0).field("caption", 1.0).open()?;
let page = photos.order_by("taken_at", Direction::Desc).limit(50).all()?;
let result = found.search("море").run()?;A row and its words change in one commit, so the list and the search never
disagree. An index of its own, store.index, suits a program that lists its
documents from somewhere else, a bucket by the same ids, or never lists them;
a bucket and an index commit apart, as two
files do. See A
table's index.
How many it finds
Ask for total to know how many documents a search finds under its
where, whatever its limit and offset: "teachers named Ivanov: 340" on
a chip, and whether a next page exists.
const teachers = await people.search({ text: 'иванов', where: { role: 'teacher' }, limit: 20, total: true })
teachers.total // { count: 340, atLeast: false }teachers = await people.search("иванов", where={"role": "teacher"}, limit=20, total=True)
teachers.total # Total(count=340, at_least=False)teachers, err := people.Search(ctx, "иванов", search.Where{"role": "teacher"}, search.Limit(20), search.Total())
teachers.Total // &search.Counted{Count: 340, AtLeast: false}; nil without search.Total()let teachers = people.search("иванов").filter(eq("role", "teacher")).limit(20).total().run()?;
teachers.total // Some(Total { count: 340, at_least: false })countis exact up to 10,000. Past that the search stops counting and answers 10,000 withatLeast: at least that many, never an estimate (contract SRCH-18).- It counts each document the search's words find, as the search read them,
a corrected word and the other keyboard layout included, that its
wherepasses. A search still can't page past its 1000th hit, buttotalsays how many there are. - A next page exists when
atLeastis set, or whenoffsetplus the hits given is less thancount. - Counting reads every document the words' lists hold, which a search alone
mostly skips, so it costs more. Without
totala search costs what it did. - A search by a vector with
totalisinvalid: a vector finds every document that has one. - In a table's index, a row SQLite removed for a
replacewithout telling any trigger stays counted until a search meets it or maintenance takes it out.
Async Rust
With the async feature, tinystore::aio::search has the same indexes, and
each call that reads, writes or waits returns a future. Open the index from
an aio::Store, and add .await. Rust with
async says where each call runs and what
a dropped future does.
use tinystore::Options;
use tinystore::aio::Store;
use tinystore::aio::search::eq;
let store = Store::open("data", Options::default())?;
let articles = store.index::<Article>("articles").field("title", 2.0).field("body", 1.0).filters(["author_id"]).open()?;
articles.set("a-17", &bread).await?;
articles.set_many([("a-18", &rye), ("a-19", &spelt)]).await?;
let result = articles.search("хлеба").filter(eq("author_id", &42)).run().await?;
let one = articles.get("a-17").await?; // Some(bread)
let gone = articles.delete("a-17").await?; // true: there was one
articles.ready().await?; // returns once a rebuild has switched inget answers in its first poll when one of the file's readers is free, and
otherwise on the store's threads. Opening an index is still a plain call. The
answers are the same types as in
the blocking API: Found, Hit, Status and Listed, and the filters
eq, is_in, range, missing, or and and.
| Blocking | Async |
|---|---|
articles.set("a-17", &bread)? | articles.set("a-17", &bread).await? |
articles.id("d-1").vector(&v).set(&doc)? | articles.id("d-1").vector(&v).set(&doc).await? |
articles.set_many(documents)? | articles.set_many(documents).await? |
articles.get("a-17")? | articles.get("a-17").await? |
articles.delete("a-17")? | articles.delete("a-17").await? |
articles.search("хлеба").run()? | articles.search("хлеба").run().await? |
articles.status()?, articles.ready()? | articles.status().await?, articles.ready().await? |
store.drop_index("articles")? | store.drop_index("articles").await? |
store.search("algebra").among(…).run()? | store.search("algebra").among(…).run().await? |
tinystore::search::list(&store)? | tinystore::aio::search::list(&store).await? |
tinystore::search::maintain(&store)? | blocking: tinystore::search::maintain(store.blocking())? |
Three rules are Search's own:
- A set makes the document's JSON when you call it, and its words in the
future's first poll. When its documents add up to more than 4 KiB of JSON,
for example in a
set_manyof many documents, it makes the words on the store's own threads instead. - Each hit is decoded on the store's threads, so the document type must be
Send + 'static. A search refused for its text, its limit or its vector fails in the first poll. - On a store opened without background work,
readyruns the maintenance itself, on the store's threads.
Index::from(index) and index.blocking() cross between the two APIs. Both
give the same index, never a second one. A table's index has the same awaited
search, status and ready: see A table's index.
In these guides
| Page | Covers |
|---|---|
| Fields and weights | which text is read, and how much each field counts |
| Typos | the nearest word, corrected, typoTolerance |
| As you type | prefix: the last word, or each, as a start |
| Keyboard layouts | layouts: a word typed with the other layout on |
| Abbreviations and synonyms | synonyms for every document, aliases for one |
| Show what matched | matches and snippet: where each hit matched |
| Filters | where, lists, ranges, search.or |
| Vectors | dimensions, exact search, recall and clusters |
| Words and vectors together | vectorWeight, minSimilarity, rerank |
| A table's index | db.searchIndex, triggers, ready |
| Ask several indexes at once | store.search: groups, more, merged by rank |
| Rebuilds | changing fields and filters while the index answers |
New to Search? Finding old messages in the Handbook indexes a chat's messages, and How search finds explains the index.
Reference
Bun and Node · Python · Go · Rust