Search
Introduction
@plinthjs/search gives you a small full-text search layer. You describe what you want with a fluent Builder (a phrase, some where filters, an ordering, a limit), and an Engine that owns the indexed documents decides which ones match. The package ships a dependency-free, in-memory engine called CollectionEngine, which is the default and is a good fit for small data sets, development and tests. When you outgrow it, you write your own engine (or wrap a hosted search service) and register it by name; the code that builds queries does not change.
pnpm add @plinthjs/searchThree pieces work together:
- A searchable record: anything that can report which index it belongs to, its stable key, and the flat document to index.
- An engine: stores documents per index and answers queries.
- The
SearchManager: resolves named engines, imports records, and flushes indexes.
The package does not hook into the ORM automatically. Nothing indexes a model when you save it; you decide when to import records and when to delete them.
Making records searchable
A searchable record implements three methods. searchableAs() names the index (think of it as a table name), getSearchKey() returns the record's stable identity within that index, and toSearchableArray() returns the flat document that is actually indexed. Only fields you return from toSearchableArray() can be matched or filtered on.
import type { Searchable } from '@plinthjs/search'
class Post implements Searchable {
constructor(
public id: number,
public title: string,
public body: string,
public status: string,
) {}
searchableAs(): string {
return 'posts'
}
getSearchKey(): number {
return this.id
}
toSearchableArray(): Record<string, unknown> {
return { id: this.id, title: this.title, body: this.body, status: this.status }
}
}Keys are strings or numbers. Indexing the same key twice replaces the earlier document.
Wrapping plain data
If you only have plain objects, makeSearchable builds a Searchable for you. It takes the record and an options object: the index name, the key field (default 'id') and an optional toDocument projection (default: a shallow copy of the record).
import { makeSearchable } from '@plinthjs/search'
const row = { id: 1, title: 'Intro to Plinth', status: 'published', secret: 'x' }
const record = makeSearchable(row, {
index: 'posts',
toDocument: (r) => ({ id: r.id, title: r.title, status: r.status }),
})
record.searchableAs() // => 'posts'
record.getSearchKey() // => 1
record.toSearchableArray() // => { id: 1, title: 'Intro to Plinth', status: 'published' }getSearchKey() throws Searchable record is missing a [id] search key. when the key field is absent or is not a string or number.
Importing records
Create a SearchManager and import records into it. The manager starts with the collection driver already registered, and import groups records by the index each one reports, so a single call can span several indexes.
import { SearchManager, search } from '@plinthjs/search'
const search = new SearchManager()
search.import(undefined, [
new Post(1, 'Intro to Plinth', 'Getting started', 'published'),
new Post(2, 'Plinth routing guide', 'How routes work', 'draft'),
new Post(3, 'Caching guide', 'Remember things', 'published'),
])The first argument is the engine name; pass undefined for the default engine. import returns the manager, so calls chain. To remove an entire index, call flush(name, index):
search.flush(undefined, 'posts')To remove individual documents, call delete on the engine itself (see Using an engine directly).
Searching
search(engine, index, phrase) starts a Builder. The phrase is optional; an empty phrase matches every document in the index. Resolve the engine from the manager and run the query with one of the terminal methods.
const engine = search.engine()
search(engine, 'posts', 'plinth').keys() // => [1, 2]
search(engine, 'posts', 'plinth').get() // => the matching documents, in result orderThe terminal methods are:
| Method | Returns |
|---|---|
keys() | The keys of the matches, in result order |
get() | The matched documents (the objects from toSearchableArray()) |
raw() | { hits, total }, each hit being { key, document, score } |
paginate(perPage, page?) | A length-aware page (see below) |
raw() is useful when you need the grand total: total counts every match before take is applied.
search(engine, 'posts', 'plinth').take(1).raw()
// => { hits: [{ key: 1, document: {...}, score: 1 }], total: 2 }How the in-memory engine matches
CollectionEngine lowercases the phrase and splits it on any run of characters that are not letters or digits. A document matches when the text of all its fields, concatenated and lowercased, contains every token as a substring. Because it is a substring test, wor matches a document that contains world or work, and every word in the phrase must be present.
search(engine, 'posts', 'ROUTING').keys() // => [2] (case-insensitive)
search(engine, 'posts', 'wor').keys() // => [2] (substring of "work")
search(engine, 'posts', 'plinth routing').keys() // => [2] (all tokens required)Non-string field values are stringified before matching (numbers, booleans and dates are converted, arrays are joined, objects are serialised as JSON). Fields that are null or undefined contribute nothing.
Each hit carries a score, 0 for an empty phrase. Every query token earns its best weight in the document: 3 for a whole word, 2 for a word that starts with it, 1 for a match inside a word. The score is the sum, so documents that match more tokens, or match them more exactly, rank first. Without an explicit orderBy, ties are broken by key, which keeps the order stable and predictable.
By default every token must match. new CollectionEngine({ match: 'any' }) returns documents that match at least one token, ranked by score.
Filtering
Chain where for equality filters and whereIn for membership. All constraints must hold. Comparison is loose and works on the stringified value, so 1 equals '1'.
search(engine, 'posts', 'guide').where('status', 'published').keys() // => [3]
search(engine, 'posts').whereIn('id', [1, 3]).keys() // => [1, 3]Filters only see fields present in the indexed document. If you filter on status, toSearchableArray() must return status.
For anything those two cannot express, query(callback) receives the matched documents and returns the subset (and order) you want to keep. It runs before orderBy.
search(engine, 'posts')
.query((documents) => documents.filter((doc) => String(doc['title']).length > 14))
.keys() // => [1, 2]The callback may filter, reorder or even return new objects. Returned documents are matched back to hits by reference first, then by the document's key field (id by default; set new CollectionEngine({ keyField: 'uuid' }) to change it), then by deep equality. A document that matches no hit is dropped.
Ordering and limiting
orderBy(field, direction) sorts by a document field, 'asc' by default. Numbers compare numerically; everything else compares by its stringified form. Add more orderBy calls to break ties. When no clause decides the order, the engine falls back to score and then key.
search(engine, 'posts').orderBy('title', 'desc').keys() // => [2, 1, 3]
search(engine, 'posts').orderBy('id', 'desc').take(2).keys() // => [3, 2]take(count) limits the hits returned. It affects keys(), get() and raw().hits, but raw().total still reports every match.
Pagination
paginate(perPage, page) returns one page and length-aware metadata. The page number is 1-based and defaults to 1.
const page = search(engine, 'posts').orderBy('id', 'desc').paginate(2, 2)
// => {
// data: [{ id: 1, ... }],
// total: 3,
// perPage: 2,
// currentPage: 2,
// lastPage: 2,
// }lastPage is ceil(total / perPage) and never drops below 1, even when nothing matched. take is ignored by paginate; the page slice is what limits the result.
Resolving engines by name
The manager builds each engine on first use and caches it, so search.engine() returns the same instance every time. Configure the default and register extra engines through the constructor:
const search = new SearchManager({
default: 'collection',
engines: {
typesense: () => new MyTypesenseEngine(),
},
})
search.engine('typesense') // built once, then cached
search.getDefaultEngine() // => 'collection'You can also register a driver later with extend(name, factory), which replaces any engine already registered under that name and discards its cached instance:
search.extend('typesense', () => new MyTypesenseEngine())Asking for a name with no factory throws Search engine [name] is not defined.
Writing an engine
An engine is any object implementing the Engine interface. Five methods are all it needs:
| Method | Purpose |
|---|---|
update(index, documents) | Upsert { key, document } pairs into an index |
delete(index, keys) | Remove documents by key |
search(index, query) | Return { hits, total } for a SearchQuery |
paginate(index, query, perPage, page) | Return one page of hits plus the grand total |
flush(index) | Drop every document in an index |
The SearchQuery you receive is the builder's state: query (the raw phrase), wheres, whereIns, orders, limit and callbacks. A remote engine would translate these into calls to its service. Every method may return its value or a promise (MaybePromise), so a remote engine can simply be async. The builder has async terminals (rawAsync(), keysAsync(), getAsync(), paginateAsync()) and the manager has importAsync() and flushAsync(); use those with an async engine. The synchronous terminals keep working with synchronous engines such as the collection engine, and throw a clear error if an engine hands back a promise.
The simplest useful engine delegates to a CollectionEngine, which is a convenient way to add logging or metrics:
import { CollectionEngine, SearchManager, search } from '@plinthjs/search'
import type {
Engine,
EngineResults,
IndexedDocument,
SearchKey,
SearchQuery,
} from '@plinthjs/search'
class LoggingEngine implements Engine {
private readonly inner = new CollectionEngine()
readonly calls: string[] = []
update(index: string, documents: readonly IndexedDocument[]): void {
this.calls.push(`update:${documents.length}`)
this.inner.update(index, documents)
}
delete(index: string, keys: readonly SearchKey[]): void {
this.calls.push('delete')
this.inner.delete(index, keys)
}
search(index: string, query: SearchQuery): EngineResults {
this.calls.push(`search:${query.query}`)
return this.inner.search(index, query)
}
paginate(index: string, query: SearchQuery, perPage: number, page: number): EngineResults {
return this.inner.paginate(index, query, perPage, page)
}
flush(index: string): void {
this.inner.flush(index)
}
}
const search = new SearchManager({
default: 'logging',
engines: { logging: () => new LoggingEngine() },
})
search.import(undefined, [new Post(1, 'Hello World', 'first post', 'published')])
const engine = search.engine() as LoggingEngine
search(engine, 'posts', 'hello').keys() // => [1]
engine.calls // => ['update:1', 'search:hello']Using an engine directly
The builder and manager are conveniences. An engine can be used on its own, which is how you remove single documents or index data without a Searchable:
const engine = new CollectionEngine()
engine.update('posts', [
{ key: 1, document: { title: 'Hello' } },
{ key: 2, document: { title: 'World' } },
])
engine.delete('posts', [1])
search(engine, 'posts').keys() // => [2]Testing
Because CollectionEngine lives entirely in memory, tests need no setup beyond creating a fresh SearchManager. See Testing for the other in-memory drivers and fakes the framework ships with.
import { expect, it } from 'vitest'
it('finds published posts', () => {
const search = new SearchManager()
search.import(undefined, [
new Post(1, 'Plinth', 'a', 'published'),
new Post(2, 'Plinth', 'b', 'draft'),
])
expect(search(search.engine(), 'posts', 'plinth').where('status', 'published').keys()).toEqual([
1,
])
})