Search / A table's index
A table's index
An index opened from an application's database follows one of its tables. The table owns the rows; the index finds them again by their words and vectors, and changes in the same commit as each row. There is no second copy to keep in sync, and no moment when the table and the index disagree.
interface Article {
id: number
slug: string
title: string
body: string
author_id: number
published: number
}
const db = await store.database('blog', { migrations: `${import.meta.dirname}/migrations` })
const articles = db.searchIndex<Article>('articles_search', {
table: 'articles',
key: 'slug',
fields: { title: 2, body: 1 },
filters: ['author_id', 'published'],
vectors: { column: 'embedding', dimensions: 1024 },
})
await articles.ready() // the rows the table already holds, read once
const { hits } = await articles.search({ text: 'хлеба', where: { author_id: 7, published: true } })
hits[0] // { id: 'bread', value: { id: 1, slug: 'bread', title: 'Как испечь хлеб', … }, score: … }db = await store.database("blog", migrations=Path(__file__).parent / "migrations")
articles = db.search_index(
"articles_search", Article,
table="articles",
key="slug",
fields={"title": 2, "body": 1},
filters=["author_id", "published"],
vectors=tinystore.Vectors(column="embedding", dimensions=1024),
)
await articles.ready() # the rows the table already holds, read once
result = await articles.search("хлеба", where={"author_id": 7, "published": True})db, err := sqldb.Open(ctx, store, "blog", sqldb.Migrations(os.DirFS("migrations")))
articles, err := search.OpenIndex[Article](db, "articles_search",
search.Table("articles"),
search.Key("slug"),
search.Fields{"title": 2, "body": 1},
search.Filters("author_id", "published"),
search.Vectors{Column: "embedding", Dimensions: 1024})
err = articles.Ready(ctx) // the rows the table already holds, read once
result, err := articles.Search(ctx, "хлеба", search.Where{"author_id": 7, "published": true})let db = store.database("blog").migrations("migrations").open()?;
let articles = db
.search_index::<Article>("articles_search")
.table("articles")
.key("slug")
.field("title", 2.0)
.field("body", 1.0)
.filters(["author_id", "published"])
.vectors("embedding", 1024)
.open()?;
articles.ready()?; // the rows the table already holds, read once
let found = articles.search("хлеба").filter(eq("author_id", &7)).filter(eq("published", &true)).run()?;| Option | What it says |
|---|---|
table | the table whose rows the index holds |
key | a column, or columns, of unique values that name a row, a hit's id; the primary key unless set |
fields | the columns whose words are read, with their weights |
filters | the columns a search may keep to; a boolean matches the 1 or 0 SQLite keeps |
vectors | the column of vectors your program fills, and their dimensions |
A hit's value is its row as db.all reads it, every column. The index
lives in the database's file, sql/blog.db, beside the table. A where can
also hold a statement of the database in a list's place, to keep a search
to the rows it gives: The rows of a statement.
The rows of one search count together, as the rows of one db.all do. If
they pass 64 MiB, or more than the store's memory has free, the search fails
with a limit error instead of returning fewer hits. Ask for fewer hits, or
keep large columns such as files in a table of their own.
A key of several columns
A table whose rows are named by two columns together, task 6 of space NW,
needs no surrogate id. Its primary key is the index's key unless key names
other columns, and a unique index of exactly those columns serves as well:
create table tasks (space text not null, n integer not null, title text not null, primary key (space, n));const tasks = db.searchIndex<Task>('tasks_search', { table: 'tasks', key: ['space', 'n'], fields: { title: 1 } })
const found = await tasks.search('экран')
found.hits[0] // { id: '["NW",6]', value: { space: 'NW', n: 6, title: 'экран входа' }, score: … }tasks = db.search_index("tasks_search", Task, table="tasks", key=("space", "n"), fields={"title": 1})tasks, err := search.OpenIndex[Task](db, "tasks_search", search.Table("tasks"), search.Key("space", "n"), search.Fields{"title": 1})let tasks = db.search_index::<Task>("tasks_search").table("tasks").key(["space", "n"]).field("title", 1.0).open()?;A hit's id is the key's values as a JSON array, ["NW",6], which reads
back in every language, and the row in value carries every column. To keep
a search to one space, list space in filters. Each row is held once by
its key's values together, and follows every change as an index keyed by
one column does (contract SRCH-19). A row with no value in a key column has
no key the index can find it by, and its write fails with an invalid error.
Bun, Node, Python and Go open a handle at its first call, so a key that
isn't one, or a table without a primary key, fails there. Call await index.status() once at start-up, after the migrations, so that the mistake
fails before a user types the first search.
Every change reaches it
Opening the index puts triggers on the table that note each changed row's key. Every transaction of the file reads those rows into the index before it commits:
- an insert, an update or a delete by any statement, a trigger, a cascade or a migration reaches the index in the commit that makes it; a rollback changes neither (contract SRCH-07);
- a row SQLite removes to make room for another, as
insert or replace,replace intoandupdate or replacedo when the other row takes a value of a unique column that is not the key, fires no delete trigger, so the index still holds it. The first search that meets it leaves it out and fills its page with the hits after it, and the next maintenance takes it out of the index, unless the row is back by then; - a write by another program beside the store,
tinystore sql --writeor a SQLite shell, reaches it at the store's next write to the file, or within a second (contract SRCH-08); - a migration that rebuilds the table, a new table copied and renamed, is read again whole.
await db.exec`update articles set title = ${'Хлеб без дрожжей'} where slug = ${'bread'}`
await articles.search({ text: 'дрожжей' }) // the new title, alreadyawait db.exec("update articles set title = ? where slug = ?", "Хлеб без дрожжей", "bread")
await articles.search("дрожжей") # the new title, alreadyA write the index cannot take fails alone: a row whose embedding is not a
vector of the index's dimensions fails its own insert, and the writes beside
it in the shared commit go on.
Vectors in a column
The vectors column is a blob of little-endian 32-bit floats, one vector a
row, or null for a row found by its words only:
alter table articles add column embedding blob;const bytes = new Uint8Array(new Float32Array(vector).buffer)
await db.exec`update articles set embedding = ${bytes} where slug = ${slug}`await db.exec("update articles set embedding = ? where slug = ?", struct.pack(f"<{len(vector)}f", *vector), slug)bytes := make([]byte, 4*len(vector))
for i, f := range vector {
binary.LittleEndian.PutUint32(bytes[4*i:], math.Float32bits(f))
}
_, err = db.Exec(ctx, `update articles set embedding = ? where slug = ?`, bytes, slug)let bytes: Vec<u8> = vector.iter().flat_map(|f| f.to_le_bytes()).collect();
db.exec(sql!("update articles set embedding = ? where slug = ?", bytes, slug))?;The program fills the column when it has the vector, often from a job that asks the model after the row is saved. Until then the row is found by its words.
Searching inside a transaction
In Rust, a transaction searches the index through tx.with(&index), and sees
what the transaction wrote, before it commits:
let found = db.tx(|tx| -> tinystore::Result<usize> {
tx.exec(sql!("update articles set title = ? where slug = ?", "Хлеб без дрожжей", "bread"))?;
Ok(tx.with(&articles).search("дрожжей").run()?.hits.len()) // 1: the transaction's own write
})?;Bun, Node, Python and Go search outside a transaction. A search finds what a transaction wrote once the transaction commits, so search after it returns.
Settings and dropping
The index's fields, filters, weights and vectors change as a store's index's do: open it with other settings under the same name, and it reads the table again beside itself while it answers. Never version an index's name for this. See Rebuilds.
Another table or key works the same way. Open the index with it under the same name, and the store reads the new table beside the index while the old table's rows answer every search and the index takes the old table's writes. Once the new table is read, the index switches to it in one commit (contract SRCH-20):
const articles = db.searchIndex<Article>('articles_search', { table: 'articles_v2', key: 'slug', fields: { title: 2, body: 1 } })
await articles.status() // { state: 'rebuilding', done: 0 }: the rows of articles answer until the switch
await articles.ready() // switched: the rows of articles_v2, by slugarticles = db.search_index("articles_search", Article, table="articles_v2", key="slug", fields={"title": 2, "body": 1})
await articles.ready()- A write to the new table during the read reaches the rows beside, through triggers of their own, so that the new rows miss nothing. Two sets of triggers can sit on one table, when only the key changes, and never collide.
- The switch's commit takes the old table's triggers off and puts the index's own on the new table. From then on a write to the old table no longer reaches the index.
- A restart goes on where the read stopped.
- With
rebuild: 'manual', the change isinvaliduntilreindexasks for it, as for a field. status()saysrebuildingwhile the new table is read, and itsdonestays 0 until the switch.
await db.dropSearchIndex('articles_search') // true: its triggers off the table, its rows droppedawait db.drop_search_index("articles_search")dropped, err := search.Drop(ctx, db, "articles_search")db.drop_search_index("articles_search")?;A drop runs in a transaction of its own. Inside db.tx it fails with an
invalid error and changes nothing, so drop the index after the transaction.
A table a migration drops takes its index with it: the next time an index of that database opens, or one is dropped, the store drops each index whose table is gone and logs it once (contract SRCH-21). A migration that rebuilds a table by SQLite's twelve steps, a new table copied and renamed, leaves the table there, and its index is read again whole.
If the table is renamed while its index exists, for example by a SQLite shell beside the store, the index can no longer read the table's rows. Writes to the rest of the database go on, and the store logs each row that it leaves out of the index. A write to the renamed table fails with an invalid error that names the index, so drop the index and open a new one on the new name.
Async Rust
With the async feature, a database opened from tinystore::aio::Store
opens its index with the same builder. Its search, status and ready
return futures, as Rust with async
describes:
Each hit's row is read on the store's own threads, in the snapshot that its
search read, so the row type must be Send + 'static. If you drop ready,
it stops waiting, and the table's rows are still read in the background.
Inside a transaction a search stays blocking, as every call in a transaction
is. tx.with(&articles) takes the async handle and gives the same handle as
in the blocking API, which sees what the transaction wrote. The Search
guide lists every awaited call of an index.
Why this design?
Why the index follows the table. With a separate search service, the program writes the row and then the document, and every bug, crash or retry between the two leaves them apart. Teams then write jobs that compare and repair. Triggers note each change inside SQLite, and every commit brings the index up to date before it ends, so the two cannot drift.
Why triggers note keys, not documents. A trigger runs inside SQLite's statement, where the index's own work, cutting text into words, cannot run. So a trigger writes only the changed row's key, and the store reads those rows once, at the commit: a row updated ten times in a transaction is indexed once.
See also
- Search: the engine's overview.
- Buckets and queues in a database: what else can live in a database's file.
- Finding old messages in the Handbook indexes a chat's messages this way.