---
url: /reference/search.md
---

# @signaldb/search

```ts
import { search, createSearchAdapter } from '@signaldb/search'
```

`@signaldb/search` keeps a search index in sync with a collection and adds a reactive `search()` method to it. It does not depend on any search library. You connect the one you choose with `createSearchAdapter`. The [Full-Text Search guide](/queries/full-text-search/) shows how to use it, with adapters for FlexSearch, MiniSearch and uFuzzy.

```ts
const Posts = withPlugins(
  new Collection<Post>('posts', dataAdapter, { reactivity }),
  search({ adapter: searchAdapter, fields: { title: 1, body: 1 } }),
)

const cursor = Posts.search('offline', { limit: 10 })
cursor.fetch()     // the matching posts, most relevant first
cursor.isLoading() // true while the index is built or the search is answered
```

## `createSearchAdapter(definition)`

Connects a search library. Every member may answer synchronously or return a promise. The plugin calls them one at a time, in the order the changes happened, so an asynchronous library never sees an update overtake another.

```ts
interface SearchAdapter<T, I> {
  add(item: T): void | Promise<void>
  remove(id: I): void | Promise<void>
  search(term: string, options: { limit: number }): I[] | Promise<I[]>
  clear(): void | Promise<void>
  load?(): boolean | Promise<boolean>
  save?(): void | Promise<void>
}
```

* `add(item)` indexes an item under its `id`. Items from the initial build carry only the fields the plugin's `fields` option projects them to, and the collection's `transform` is applied to them. Items from writes are complete and untransformed.
* `remove(id)` removes an id. An id that is not indexed is ignored.
* `search(term, { limit })` returns the ids of the matching items, most relevant first.
* `clear()` empties the index before a rebuild.
* `load()` is optional. It restores a saved index and resolves to `true` when it did, which replaces the initial build. Resolve to `false` to build the index from the collection.
* `save()` is optional. It is called debounced after changes and after a build, and when the collection is disposed with changes still unsaved. It is never called while the index is being built.

## `search(options)`

Creates the plugin. Install it with [`withPlugins`](/reference/core/withplugins/).

* `adapter` (required) is the search library, created with `createSearchAdapter`.
* `fields` is a [projection](/queries/#projection) for the initial build, for example `{ title: 1, body: 1 }`. Reading only the searched fields keeps the build cheap, above all across the worker boundary of a `WorkerDataAdapter`. Default is every field.
* `limit` is the number of results a search returns when it does not pass its own (default `20`).
* `chunkSize` is the number of items the initial build indexes before it yields to the event loop (default `1000`).
* `saveDelay` is the number of milliseconds after the last change before `save()` is called (default `1000`).
* `onError(error)` receives errors from the adapter. Without it, each distinct error is logged once with `console.error`.

The plugin builds the index once the collection is [ready](/reference/core/collection/#ready), from a single read with `fields`, and then follows the collection's `added`, `changed` and `removed` events. A write that lands while the index is being built is not overwritten by the older state from that read. Writes synced through `@signaldb/sync` fire the same events and are indexed as well. Changes that bypass the collection, such as writes from another tab to the same storage, are not. Call `rebuildSearchIndex()` after those.

## `collection.search(term, options?)`

⚡️ this function is reactive!

Searches the collection and returns a cursor.

* `limit` is the maximum number of results (default is the plugin's `limit`).
* `async: true` reads the result with `await` instead of reactively, outside of a reactive scope. It waits for the index to be built.

The cursor has three methods.

* `fetch()` returns the matching items, most relevant first, with the collection's `transform` applied. With `async: true` it returns a promise.
* `count()` returns the number of matching items. With `async: true` it returns a promise.
* `isLoading()` returns `true` while the index is being built, the search library has not answered yet, or the matching items have not been read yet.

A reactive read reruns when a write changes the index, so a new item that matches shows up without a new search. Until the result is known, `fetch()` returns an empty list. Read `isLoading()` to tell that apart from a search without results. An empty or blank term returns no results without asking the search library.

## `collection.rebuildSearchIndex()`

Clears the index and builds it again from the collection. Returns a promise that resolves once the index is rebuilt, or rejects when the adapter failed. Searches meanwhile report `isLoading()` and return no results.
