# Search

Built-in full-text search.

The [recommended preset](/config#recommendedpreset) includes full-text search, with no setup. Readers open it with <kbd>⌘</kbd> <kbd>K</kbd>, <kbd>Ctrl</kbd> <kbd>K</kbd> or the search button.

## Built-in Search [#built-in-search]

The build indexes each page's title, description, headings and text, in one index per language. The browser searches the index of the page's language, so search works on a static host.

Pass search options to the preset's `search`:

```ts title="vuesho.config.ts"
import { createSite, recommendedPreset } from "vuesho/config";
import { defineDocs } from "vuesho/content";

const docs = defineDocs();

export default createSite(docs.toSource()).plugins(
  recommendedPreset({
    search: { filter: ({ page }) => !page.url.startsWith("/changelog") }, // [!code highlight]
  }),
);
```

### SearchOptions

| Prop                 | Type                                                                                                                  | Description                                                                                                                                                                                                                                                                                                                                                          |
| -------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `render?`            | `"static" \| "dynamic" \| undefined`                                                                                  | - `static`: the build exports each language's index, which the browser loads on the first search and searches itself, so search works on static hosting. - `dynamic`: the server searches, so the browser downloads no index. The site needs a server. A search service has neither. Default: `` `dynamic` when the content renders on demand, `static` otherwise `` |
| `filter?`            | `((env: PageEnv<AppShape>) => boolean) \| undefined`                                                                  | Leaves out a page when it returns `false`. The search indexes content pages, so `env.page` is set, and never a page with `noindex`, but one shown in the fallback language, which readers of its language find there.                                                                                                                                                |
| `buildIndex?`        | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<SearchIndex>) \| undefined` | A page's search index, from its page data and `getPageStructuredData()` by default. Return `tag` to filter results by it in the dialog, and `breadcrumbs` to replace the page tree folders the results show.                                                                                                                                                         |
| `additionalIndexes?` | `SearchIndex[] \| ((this: Context<AppShape>, env: LangEnv<AppShape>) => Awaitable<SearchIndex[]>) \| undefined`       | Search indexes added to the pages', like custom pages' or another site's: a list for every language, or a function of `{ lang }` that gives each language's. `filter` and `buildIndex` don't apply to them.                                                                                                                                                          |

### Leaving Pages Out [#leaving-pages-out]

`filter` keeps a page in the index when it returns `true`. `page.data` has your frontmatter types, so a field from the [frontmatter schema](/markdown/collections#frontmatter-schema) can leave pages out:

```ts title="vuesho.config.ts"
import { pageSchema } from "vuesho/schema"; // [!code ++]
import { z } from "zod"; // [!code ++]

const docs = defineDocs({
  docs: { schema: pageSchema.extend({ unlisted: z.boolean().default(false) }) }, // [!code ++]
});

export default createSite(docs.toSource()).plugins(
  recommendedPreset({ search: { filter: ({ page }) => !page.data.unlisted } }), // [!code highlight]
);
```

The sitemap, the RSS feed and `llms.txt` each take their own `filter`, as [SEO](/seo#excluded-pages) shows.

### Customizing the Index [#customizing-the-index]

`buildIndex` returns a page's index. Start from the default index, which `buildIndexDefault()` returns:

```ts title="vuesho.config.ts"
import { buildIndexDefault } from "vuesho/search"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset({
    search: {
      // [!code ++:5]
      async buildIndex(page) {
        const index = await buildIndexDefault.call(this, page);
        // Shows "guide" and "cli" above `guide/cli/build.md`'s results.
        return { ...index, breadcrumbs: page.path.split("/").slice(0, -1) };
      },
    },
  }),
);
```

### SearchIndex

| Prop             | Type                              | Description                                                                  |
| ---------------- | --------------------------------- | ---------------------------------------------------------------------------- |
| `id`             | `string`                          | Unique in the index. Defaults to the page's URL.                             |
| `url`            | `string`                          | The page's URL: a site path or, for another site's index, its full URL.      |
| `title`          | `string`                          | The title the results show.                                                  |
| `description?`   | `string \| undefined`             | The page's summary, left out when its text repeats it.                       |
| `breadcrumbs?`   | `string[] \| undefined`           | The page tree folders above the page, which the results show.                |
| `tag?`           | `string \| string[] \| undefined` | The tags the dialog filters results by.                                      |
| `structuredData` | `StructuredData`                  | The page's headings and the text under each, from `getPageStructuredData()`. |

Some [search services](/search/services#custom-fields) store the extra fields that `buildIndex` returns.

`additionalIndexes` adds indexes that aren't pages of a source, like a [custom page](/custom-pages) or another site's page. It takes one list for all languages, or a function that receives `{ lang }` and returns that language's list:

```ts title="vuesho.config.ts"
recommendedPreset({
  search: {
    additionalIndexes: [
      {
        id: "/showcase",
        url: "/showcase",
        title: "Showcase",
        structuredData: { headings: [], contents: [{ content: "Sites built with Acme." }] },
      },
    ],
  },
});
```

### Tags [#tags]

Tags filter the results, with a tab per tag in the dialog's footer. Return each page's `tag` from `buildIndex`, and list the tabs in `tags`:

```ts title="vuesho.config.ts"
import { buildIndexDefault } from "vuesho/search";

createSite(docs.toSource()).plugins(
  recommendedPreset({
    search: {
      async buildIndex(page) {
        const index = await buildIndexDefault.call(this, page);
        return { ...index, tag: page.path.startsWith("api/") ? "api" : "guide" }; // [!code highlight]
      },
      // [!code highlight:4]
      tags: [
        { name: "Guide", value: "guide" },
        { name: "API Reference", value: "api" },
      ],
      // The tab selected when the dialog opens.
      defaultTag: "guide",
      // Lets the reader clear the tab, to search every page.
      allowClear: true,
    },
  }),
);
```

### Searching on the Server [#searching-on-the-server]

With `render: "dynamic"`, the server runs each query, so the browser downloads no index. The site then needs a [server](/deploying):

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({ search: { render: "dynamic" } }), // [!code highlight]
);
```

`render` is `"dynamic"` by default when content renders on request, like a [dynamic source](/dynamic-rendering). With `render: "static"` on such a site, the index holds only the pages known when the site builds.

Each language's search API is at `/_vuesho/search/<lang>`, under the [base path](/deploying#base-path), and returns the results as JSON:

```bash
# `query` is required. `tag` takes tags separated by commas, and `limit` caps the results.
curl "https://docs.acme.dev/_vuesho/search/en?query=deploy&tag=guide&limit=10"
```

## Search Engines [#search-engines]

The built-in search runs on MiniSearch, and ZBSearch or FlexSearch can replace it:

| Engine               | Matches                         | Index size               |
| -------------------- | ------------------------------- | ------------------------ |
| MiniSearch (default) | Prefixes, and words with a typo | The smallest             |
| ZBSearch             | Whole words and prefixes        | About 1.2 times as large |
| FlexSearch           | Any part of a word              | About 3 times as large   |

### MiniSearch [#minisearch]

[MiniSearch](https://github.com/lucaong/minisearch) splits text into words in every language, CJK included, and splits a name at its dots, so `useFakeTimers` finds `vi.useFakeTimers()`.

A stemmer turns each word into its stem, so "deploying" matches "deploy". `stemmer` takes a module whose default export is the stemmer, by a path from the project root or a package export. `@zbsearch/stemmers` has stemmers for 32 languages:

```npm
npm i @zbsearch/stemmers
```

```ts title="src/search-stemmer.ts"
export { stemmer as default } from "@zbsearch/stemmers/english";
```

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({ search: { stemmer: "/src/search-stemmer.ts" } }), // [!code highlight]
);
```

The stemmer receives each word in lowercase, and the language tag of its page's index. A site in several languages stems each language with its own stemmer:

```ts title="src/search-stemmer.ts"
import { stemmer as english } from "@zbsearch/stemmers/english";
import { stemmer as german } from "@zbsearch/stemmers/german";

export default (word: string, lang: string) =>
  lang.startsWith("de") ? german(word) : english(word);
```

### MiniSearchPluginOptions

| Prop       | Type                  | Description                                                                                                                                                                                                                                                                                                                                    |
| ---------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stemmer?` | `string \| undefined` | A module whose default export stems the words of the pages and of each query, like `(word, lang) => stem(word)`: it receives a word in lowercase and the language tag of its index, and returns its stem. It is a package export or a path from the project root, like `/src/search-stemmer.ts`, which the server and the browser both import. |

### ZBSearch [#zbsearch]

[ZBSearch](https://www.zbsearch.dev) splits text into words in every language, and takes its own tokenizers, components and plugins. Install it, turn off the preset's search, and add its plugin:

```npm
npm i zbsearch
```

```ts title="vuesho.config.ts"
import { zbsearchPlugin } from "vuesho/search/zbsearch"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset(), // [!code --]
  recommendedPreset({ search: false }), // [!code ++]
  zbsearchPlugin(), // [!code ++]
);
```

Stemming and typo tolerance are off by default. Turn them on with `tokenizer` and `search`:

```ts title="src/search-tokenizer.ts"
export default { language: "english", stemming: true };
```

```ts title="vuesho.config.ts"
zbsearchPlugin({
  // A word of the query may differ from the text by one letter.
  search: { tolerance: 1 },
  // "deploying" matches "deploy".
  tokenizer: "/src/search-tokenizer.ts", // [!code highlight]
});
```

`tokenizer`, `components` and `plugins` take a module, by a path from the project root or a package export, whose default export is the value. The tokenizer applies to every language's index.

`zbsearchPlugin()` takes the [built-in search](#built-in-search)'s options, the [dialog options](#dialog-options), and these:

### ZBSearchPluginOptions

| Prop          | Type                           | Description                                                                                                                                                                                                                                                                                                                  |
| ------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `language?`   | `string \| undefined`          | The tokenizer's language, a name ZBSearch knows, like `english`, which sets how it splits text into words. It brings no stemmer or stop words; `tokenizer` sets those. Default: `` "multilingual", the words of every language by `Intl.Segmenter` ``                                                                        |
| `tokenizer?`  | `string \| undefined`          | A module whose default export is the database's tokenizer, instead of `language`: a ZBSearch tokenizer config, like `{ language: "english", stemming: true }`, or a custom tokenizer. It is a package export or a path from the project root, like `/src/search-tokenizer.ts`, which the server and the browser both import. |
| `search?`     | `ZBSearchOptions \| undefined` | The search options, on the server and in the browser.                                                                                                                                                                                                                                                                        |
| `components?` | `string \| undefined`          | A module whose default export is the components of the database and its plugins, which the server and the browser both import, like `tokenizer`.                                                                                                                                                                             |
| `plugins?`    | `string \| undefined`          | A module whose default export is a list of database plugins, which the server and the browser both import, like `tokenizer`. With plugins, the schema has `embeddings`, a `vector[512]` that a plugin can fill, and a search takes `mode: "vector"`.                                                                         |

### FlexSearch [#flexsearch]

[FlexSearch](https://github.com/nextapps-de/flexsearch) matches any part of a word. Install it, turn off the preset's search, and add its plugin:

```npm
npm i flexsearch
```

```ts title="vuesho.config.ts"
import { flexsearchPlugin } from "vuesho/search/flexsearch"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset(), // [!code --]
  recommendedPreset({ search: false }), // [!code ++]
  flexsearchPlugin({ languages: { ja: { encoder: "CJK" } } }), // [!code ++]
);
```

`flexsearchPlugin()` takes the [built-in search](#built-in-search)'s options, the [dialog options](#dialog-options), and these:

### FlexsearchPluginOptions

| Prop         | Type                                                | Description                                                                                   |
| ------------ | --------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `document?`  | `IndexConfig \| undefined`                          | The index options for every language.                                                         |
| `languages?` | `Partial<Record<string, IndexConfig>> \| undefined` | The index options for a language, by key, over `document`, like `{ ja: { encoder: "CJK" } }`. |

A static index takes only `tokenize`, `resolution` and an `encoder` name, like `"CJK"`. With `render: "dynamic"`, `document` takes any [FlexSearch index option](https://github.com/nextapps-de/flexsearch#index-options), like a custom `Encoder`:

```ts title="vuesho.config.ts"
import { Charset, Encoder } from "flexsearch";

flexsearchPlugin({
  render: "dynamic", // [!code highlight]
  document: { encoder: new Encoder({ ...Charset.LatinBalance, filter: new Set(["the", "a"]) }) },
});
```

### Semantic Search [#semantic-search]

The built-in engines match words. To find pages by meaning, like matching "make it faster" to a page on caching, use [Mixedbread](/search/services#mixedbread), which searches on the server.

## Search Dialog [#search-dialog]

Each search plugin fills the `search-dialog` [slot](/theme#slots) with a dialog, configured with the plugin's dialog options.

### Dialog Options [#dialog-options]

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({
    search: {
      // The links the dialog shows before a query.
      links: [["Getting Started", "/guide"]],
      // Opens the dialog with ⌘ / or Ctrl /.
      hotKey: [
        { key: ["Meta", "Control"], display: { mac: "⌘", other: "Ctrl" } },
        { key: "/", display: "/" },
      ],
    },
  }),
);
```

### DialogOptions

| Prop          | Type                                              | Description                                                                                                                                                                                                                                                         |
| ------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `links?`      | `[name: string, href: string][] \| undefined`     | The links the dialog shows before a query, as `[name, href]`.                                                                                                                                                                                                       |
| `hotKey?`     | `[HotKey, ...HotKey[]] \| undefined`              | The keys that open the dialog when pressed together, each with how it shows: a modifier, like `Shift` or `Control`, or a keyboard event's `key` as typed with the modifiers, like `?` with `Shift`. A list of keys matches any of them. Default: `⌘ or Ctrl, and K` |
| `delayMs?`    | `number \| undefined`                             | How long the dialog waits after a keystroke before it searches, in ms. Default: `100`                                                                                                                                                                               |
| `tags?`       | `{ name: string; value: string; }[] \| undefined` | The tags the dialog filters by, each with its shown name. A page gets its tags from `tag` in `buildIndex`.                                                                                                                                                          |
| `defaultTag?` | `string \| undefined`                             | The tag selected when the dialog opens.                                                                                                                                                                                                                             |
| `allowClear?` | `boolean \| undefined`                            | Whether a reader can clear the tag. Default: `false`                                                                                                                                                                                                                |

### Adding a Footer [#adding-a-footer]

The `search-footer` [theme slot](/theme#slots) renders in the footer of every built-in search dialog, after its tags. Fill it in your theme:

```ts title="src/theme.ts"
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";
import SearchFooter from "./SearchFooter.vue";

export default defineTheme({
  extends: defaultTheme,
  slots: { "search-footer": SearchFooter }, // [!code highlight]
});
```

### Styling Highlights [#styling-highlights]

The dialog highlights the query's words in the results with the [CSS Custom Highlight API](https://developer.mozilla.org/docs/Web/API/CSS_Custom_Highlight_API). Style them with `::highlight(fd-search)`:

```css title="src/theme.css"
::highlight(fd-search) {
  color: var(--color-fd-primary-foreground);
  background-color: var(--color-fd-primary);
}
```

### Custom Dialog [#custom-dialog]

`vuesho/ui/components/dialog/search` exports the dialog's parts, and `useIndexSearch()` returns the results. This dialog searches only the pages tagged `guide`:

```vue title="src/SearchDialog.vue"
<script setup lang="ts">
import {
  SearchDialog,
  SearchDialogContent,
  SearchDialogFooter,
  SearchDialogHeader,
  SearchDialogInput,
  SearchDialogList,
  SearchDialogOverlay,
} from "vuesho/ui/components/dialog/search";
import { useAddingSlot } from "vuesho/client";
import type { IndexValues } from "vuesho/search";
import { useIndexSearch, type SearchPluginDialogProps } from "vuesho/theme";

// The dialog options, and how the index is searched.
const props = defineProps<SearchPluginDialogProps & IndexValues>();
const emit = defineEmits<{ "update:open": [open: boolean] }>();
const { search, onSearchChange, isLoading, data, error } = useIndexSearch(
  props,
  "guide", // [!code highlight]
  { client: () => import("vuesho/search/minisearch/client") },
);
const Footer = useAddingSlot("search-footer"); // [!code highlight]
</script>

<template>
  <SearchDialog
    :search="search"
    :is-loading="isLoading"
    :data="data"
    :error="error"
    :open="open"
    @update:search="onSearchChange"
    @update:open="emit('update:open', $event)"
  >
    <SearchDialogOverlay />
    <SearchDialogContent>
      <SearchDialogHeader>
        <SearchDialogInput />
      </SearchDialogHeader>
      <SearchDialogList />
      <SearchDialogFooter>
        <Footer v-if="Footer" />
      </SearchDialogFooter>
    </SearchDialogContent>
  </SearchDialog>
</template>
```

Fill the `search-dialog` slot with it, loaded with `defineAsyncComponent()`:

```ts title="src/theme.ts"
import { defineAsyncComponent } from "vue";
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";

export default defineTheme({
  extends: defaultTheme,
  slots: { "search-dialog": defineAsyncComponent(() => import("./SearchDialog.vue")) }, // [!code highlight]
});
```

`useIndexSearch()` searches a static index or the search API, whichever the plugin serves. For ZBSearch or FlexSearch, pass `{ client: () => import("vuesho/search/zbsearch/client") }` or `vuesho/search/flexsearch/client`. Each search service has its own composable:

```ts
// Algolia, with a client of `algoliasearch/lite`.
import { useAlgoliaSearch } from "@vuesho/algolia/ui";
// Orama Cloud, with a client of `@orama/core`.
import { useOramaCloudSearch } from "@vuesho/orama-cloud/ui";
// Meilisearch: useMeilisearch(props, tag).
import { useMeilisearch } from "@vuesho/meilisearch/theme";
// Typesense: useTypesense(props, tag).
import { useTypesense } from "@vuesho/typesense/theme";
// Mixedbread, which searches on the server: useIndexSearch(props, tag), without a client.
import { useIndexSearch } from "vuesho/theme";
```

`SearchDialogList` has a slot for each kind of row:

- `item`: each result
- `table`: each table of results
- `empty`: the text shown when there are no results

A custom component highlights the query with `useHighlightQuery()`, which skips the elements with `data-highlight-ignore`:

```vue title="src/SearchResult.vue"
<script setup lang="ts">
import { useSearch } from "vuesho/ui/components/dialog/search";
import { useHighlightQuery } from "vuesho/ui/search";

defineProps<{ content: string }>();
const { query } = useSearch();
const highlight = useHighlightQuery(query);
</script>

<template>
  <p :ref="highlight">{{ content }}</p>
</template>
```

### Searching an External Index [#searching-an-external-index]

A dialog can search an index that the site doesn't build, like one that the Orama Cloud crawler fills:

1. Install `@vuesho/orama-cloud` for its dialog.
2. Turn off the preset's search, and add the dialog's styles.
3. Fill `search-dialog` with your dialog, as in [Custom Dialog](#custom-dialog).

```ts tab="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({ search: false }), // [!code highlight]
  { name: "orama-dialog", stylesheet: "@vuesho/orama-cloud/css/orama-cloud.css" }, // [!code highlight]
);
```

```vue tab="src/SearchDialog.vue"
<script setup lang="ts">
import { OramaCloud } from "@orama/core";
import { OramaSearchDialog } from "@vuesho/orama-cloud/ui";

defineProps<{ open: boolean }>();
const emit = defineEmits<{ "update:open": [open: boolean] }>();

const client = new OramaCloud({ projectId: "YOUR_PROJECT_ID", apiKey: "YOUR_PUBLIC_API_KEY" });
</script>

<template>
  <OramaSearchDialog
    :open="open"
    :client="client"
    index="crawler"
    @update:open="emit('update:open', $event)"
  />
</template>
```

## Disabling Search [#disabling-search]

`search: false` removes the index, the dialog and the search button:

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset({ search: false }), // [!code highlight]
);
```

To write a search engine or connect another service, see [Custom Search](/search/custom).
