---
url: /queries/full-text-search.md
---

# Full-Text Search

SignalDB selectors match values exactly. A `$regex` can find a word inside a field, but it scans every item, ranks nothing and does not forgive a typo. Full-text and fuzzy search are the job of a dedicated search library.

[`@signaldb/search`](/reference/search/) connects the search library of your choice to a collection. It keeps the library's index in sync with the collection and adds a reactive `search()` method to it. The package itself depends on no search library. The examples on this page use [FlexSearch](https://github.com/nextapps-de/flexsearch), [MiniSearch](https://github.com/lucaong/minisearch) and [uFuzzy](https://github.com/leeoniya/uFuzzy), but any library works that can add a document under an id, remove it again and return the ids that match a term.

## Installation

```bash
npm install @signaldb/search
```

## Setting it up

Wrap your search library with `createSearchAdapter`, and install the `search` plugin on the collection with [`withPlugins`](/reference/core/withplugins/).

```js
import { Collection, withPlugins } from '@signaldb/core'
import { createSearchAdapter, search } from '@signaldb/search'
import MiniSearch from 'minisearch'

const miniSearch = new MiniSearch({
  fields: ['title', 'body'],
  searchOptions: { prefix: true, fuzzy: 0.2 },
})

const searchAdapter = createSearchAdapter({
  add: post => miniSearch.add(post),
  remove: (id) => {
    if (miniSearch.has(id)) miniSearch.discard(id)
  },
  search: (term, { limit }) => miniSearch.search(term)
    .slice(0, limit)
    .map(result => result.id),
  clear: () => miniSearch.removeAll(),
})

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

`withPlugins` returns the collection you passed in, typed with the methods the plugin adds. In TypeScript this works with an explicit item type as well, as in `new Collection<Post>(…)`.

## Searching

`search()` returns a cursor whose results are sorted by relevance. Read it inside a reactive scope like any other query.

```js
effect(() => {
  const cursor = Posts.search(searchTerm.get(), { limit: 20 })
  if (cursor.isLoading()) return renderSpinner()
  render(cursor.fetch())
})
```

The search reruns whenever a write changes the index, so a new post that matches appears without a new search, and one that no longer matches disappears. The results are the collection's items with its `transform` applied.

Until a result is known, `fetch()` returns an empty list. This happens while the index is being built, while an asynchronous search library has not answered yet, and while an asynchronous data adapter is reading the matching items. `isLoading()` tells that apart from a search without results, as described in [Queries that are not answered immediately](/queries/#queries-that-are-not-answered-immediately). An empty or blank term returns no results.

Outside a reactive scope, pass `async: true` and await the result. It waits for the index to be built.

```js
const posts = await Posts.search('offline', { async: true, limit: 20 }).fetch()
```

## Connecting a search library

An adapter has four required members. `add` indexes an item, `remove` forgets an id, `search` returns matching ids most relevant first, and `clear` empties the index before a rebuild. Each of them may return a promise, and the plugin calls them one at a time in the order the changes happened. A library that persists its index in IndexedDB or runs in a worker therefore needs no extra care.

The MiniSearch adapter is shown [above](#setting-it-up). MiniSearch reads `fields` from the item itself and throws when asked to discard an id it does not know, which is why `remove` checks with `has()` first.

### FlexSearch

[FlexSearch](https://github.com/nextapps-de/flexsearch) is built for speed and large amounts of text. An `Index` stores no documents, only the ids it maps the text to.

```js
import { Index } from 'flexsearch'

const index = new Index({ tokenize: 'forward' })

const searchAdapter = createSearchAdapter({
  add: post => index.add(post.id, `${post.title} ${post.body}`),
  remove: id => index.remove(id),
  search: (term, { limit }) => index.search(term, { limit }),
  clear: () => index.clear(),
})
```

`tokenize: 'forward'` matches the beginning of words, so a search finds results while the user is still typing. FlexSearch's encoder options decide how forgiving it is with spelling.

### uFuzzy

[uFuzzy](https://github.com/leeoniya/uFuzzy) keeps no index at all. It searches a plain array of strings, which suits short text such as titles, names or file paths. The adapter keeps that array and the matching ids side by side.

```js
import uFuzzy from '@leeoniya/ufuzzy'

const fuzzy = new uFuzzy()
const ids = []
const haystack = []
const positions = new Map()

const searchAdapter = createSearchAdapter({
  add: (post) => {
    positions.set(post.id, ids.length)
    ids.push(post.id)
    haystack.push(post.title)
  },
  remove: (id) => {
    const position = positions.get(id)
    if (position === undefined) return
    const last = ids.length - 1
    ids[position] = ids[last]
    haystack[position] = haystack[last]
    positions.set(ids[position], position)
    positions.delete(id)
    ids.pop()
    haystack.pop()
  },
  search: (term, { limit }) => {
    const [matches, info, order] = fuzzy.search(haystack, term)
    if (!matches) return []
    const ranked = order ? order.map(position => info.idx[position]) : matches
    return ranked.slice(0, limit).map(position => ids[position])
  },
  clear: () => {
    ids.length = 0
    haystack.length = 0
    positions.clear()
  },
})
```

`remove` moves the last entry into the freed slot, so removing an item costs the same no matter how many there are. uFuzzy only ranks a result set that is small enough, up to 1000 matches unless you pass a different `infoThresh` to `search()`. For a larger one, `order` is `null` and the matches come back in array order. Since every search scans the whole array, its cost grows with the number of items, while the libraries above look terms up in an index.

## How the index stays in sync

The plugin builds the index once the collection is [ready](/reference/core/collection/#ready). It reads every item once, projected to the `fields` you pass, and adds each one to the index. From then on, it follows the collection's [events](/queries/#collection-events).

* **Inserts, updates and removals** are applied as they happen. An update removes the item and adds it again, because not every library can update a document in place, and because `replaceOne` can give an item a new id.
* **Writes during the build** are not lost. The plugin listens before it reads, and an item written while the read is in flight is not overwritten by the older state the read returns.
* **Writes synced from a server** are covered too. `@signaldb/sync` applies remote changes through the collection's own methods, so they fire the same events as local writes.

::: tip Items in `add`
Items from the initial build carry only the projected fields, and the collection's `transform` is applied to them. Items from writes are complete and untransformed. Read only plain stored fields in `add`, and both work the same.
:::

## With the other data adapters

The plugin works unchanged with every [data adapter](/data-adapters/). The events are emitted by the `Collection` itself, on the thread the collection lives on, once the data layer has confirmed a write. What differs is what the initial build costs and what the index can see.

* **`DefaultDataAdapter`** holds every item in memory, so the initial read only copies them.
* **`AsyncDataAdapter`** keeps the items in storage, so the initial read loads every item from there once. Afterwards the index lives in memory even though the collection does not. That is the price of searching text that is not in memory, and it is why the [projection](/queries/#projection) to the searched fields matters.
* **`WorkerDataAdapter`** answers the initial read in the worker and sends the result to the main thread, where it is deserialized. The projection is applied inside the worker, so only the searched fields cross the boundary. The search index itself lives on the main thread. If searching is expensive enough to cost frames, run the search library in a worker of its own and answer from there with promises. FlexSearch, for example, has a worker mode.

With `WorkerDataAdapter`, a write shows up in live queries optimistically before the worker confirms it, but its event fires only after the confirmation. The search results trail the rest of the UI by one round trip to the worker.

### What the events do not see

The events describe the writes made through this collection. The index misses every change that reaches the data some other way.

* another `Collection` writing to the same storage, such as one in another browser tab or in another process,
* code that changes the storage directly, bypassing SignalDB,
* a reload of the items from storage, for example through `DefaultDataAdapter#fetchItemsFromStorage()`.

If your application has one of these, call `Posts.rebuildSearchIndex()` when it happens. It clears the index and builds it again. Searches report `isLoading()` until it is done.

## Large collections

An external index duplicates the text it searches. Keep it to the fields people actually search, and let the library store ids rather than whole documents. FlexSearch's `Index` and MiniSearch without `storeFields` do that already.

The initial build is the expensive part. The plugin indexes `chunkSize` items at a time (1000 by default) and yields to the event loop in between, so the page stays responsive while the index fills up. Lower it if a chunk still takes too long with your library.

The build reads the collection in a single query. Reading it in pages with `skip` and `limit` would not make it cheaper, because the storage adapters shipped with SignalDB narrow a query by its selector and apply sorting and windowing afterwards, so every page would read the whole store again. To avoid the read on every start, save the index, as described next.

## Persisting the index

Most search libraries can serialize their index. Give the adapter a `load` and a `save` member, and the plugin restores the index instead of building it.

```js
const indexOptions = {
  fields: ['title', 'body'],
  searchOptions: { prefix: true, fuzzy: 0.2 },
}
let miniSearch = new MiniSearch(indexOptions)

const searchAdapter = createSearchAdapter({
  // add, remove, search and clear as above
  load: async () => {
    const snapshot = await readSnapshot('posts-search-v1')
    if (!snapshot) return false
    miniSearch = MiniSearch.loadJSON(snapshot, indexOptions)
    return true
  },
  save: () => writeSnapshot('posts-search-v1', JSON.stringify(miniSearch)),
})
```

`readSnapshot` and `writeSnapshot` stand for the storage of your choice, for example IndexedDB or the [origin private file system](/reference/opfs/).

* `load` resolves to `true` when it restored an index. The plugin then skips the initial build and only follows the events. Resolve to `false` to build the index from the collection.
* `save` is called once changes have settled for `saveDelay` milliseconds (1000 by default), after a build, and when the collection is disposed with changes still unsaved. It is never called while the index is being built, so a saved index is always complete.
* FlexSearch exports its index in parts with `index.export(callback)` and restores each part with `index.import(key, data)`. It can also keep its index in IndexedDB directly. uFuzzy has no index to save, so rebuilding its string array is all there is to do.

A saved index is a cache, and it can be older than the data. The application may have closed between a write and the next save, and every change from the [previous section](#what-the-events-do-not-see) bypasses it as well. Trust it only when every write goes through this collection in this tab, and call `rebuildSearchIndex()` whenever you know the data changed elsewhere. Put a version into the storage key and change it when you change what gets indexed, so that an old snapshot is rebuilt instead of answering searches with fields that are no longer there.
