Skip to content

Commit 2a1a585

Browse files
feat(search): add useSearchCollection composable with FTS5 full-text search (#3787)
Co-authored-by: Sébastien Chopin <atinux@gmail.com>
1 parent 55b8793 commit 2a1a585

14 files changed

Lines changed: 1446 additions & 182 deletions

File tree

‎docs/content/blog/studio-oss.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ This stable release includes everything you need to edit content in production:
6868

6969
### TipTap Visual Editor
7070

71-
The modern Notion-like editing experience for Markdown content is back with a improved version, powered by [TipTap](https://tiptap.dev/) integrated through the [Nuxt UI Editor](https://ui.nuxt.com/pro/components/editor) component:
71+
The modern Notion-like editing experience for Markdown content is back with an improved version, powered by [TipTap](https://tiptap.dev/) integrated through the [Nuxt UI Editor](https://ui.nuxt.com/components/editor) component:
7272

7373
- Rich text editing with headings, formatting, links, and more
7474
- MDC component support for inserting Vue components
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
---
2+
title: useSearchCollection
3+
description: The useSearchCollection composable provides full-text search powered by SQLite FTS5, with prefix matching, BM25 ranking, and snippets.
4+
---
5+
6+
## Usage
7+
8+
Use the auto-imported `useSearchCollection` composable to search across one or more collections. It builds an FTS5 index from content sections and provides instant ranked search results.
9+
10+
```vue [app.vue]
11+
<script setup lang="ts">
12+
const { status, search } = useSearchCollection('docs')
13+
14+
const query = ref('')
15+
const results = ref([])
16+
17+
watch(query, async (value) => {
18+
results.value = value ? await search(value) : []
19+
})
20+
</script>
21+
```
22+
23+
::note
24+
`useSearchCollection` is client-only. The FTS5 index is built in the browser using SQLite WASM.
25+
::
26+
27+
## Type
28+
29+
```ts
30+
function useSearchCollection<T extends keyof PageCollections>(
31+
collection: MaybeRefOrGetter<T | T[]>,
32+
opts?: GenerateSearchSectionsOptions & { immediate?: boolean }
33+
): {
34+
status: Ref<'idle' | 'loading' | 'ready' | 'error'>
35+
search: (query: string, opts?: SearchCollectionOptions) => Promise<SearchResult[]>
36+
init: () => Promise<DatabaseAdapter>
37+
}
38+
```
39+
40+
## API
41+
42+
### Parameters
43+
44+
- `collection`: A single collection key, an array of collection keys, or a reactive ref/getter. When the value changes, the FTS index is rebuilt for the new collections.
45+
- `opts`: (Optional) Index-building options:
46+
- `immediate`: Whether to start building the index immediately. Default is `true`. Set to `false` to defer until the first `search()` call or explicit `init()`.
47+
- `ignoredTags`: Tags to ignore when extracting section content (e.g., `['code']`).
48+
- `minHeading`: Minimum heading level to split sections on (e.g., `'h2'`). Default is `'h1'`.
49+
- `maxHeading`: Maximum heading level to split sections on (e.g., `'h4'`). Default is `'h6'`.
50+
51+
### Return Values
52+
53+
- `status`: A reactive ref indicating the index state: `'idle'`, `'loading'`, `'ready'`, or `'error'`.
54+
- `search(query, opts?)`: Execute a search query. Returns a promise with ranked results.
55+
- `query`: The search string. Supports prefix matching automatically (typing `compo` matches "composable").
56+
- `opts`: (Optional) Search options:
57+
- `limit`: Maximum results. Default is `50`.
58+
- `fields`: Restrict search to specific columns (`'title'` or `'content'`).
59+
- `minTermLength`: Skip terms shorter than this value. Default is `1`.
60+
- `weights`: Control ranking behavior.
61+
- `title`: Boost factor for title matches. Default is `10`.
62+
- `content`: Boost factor for content matches. Default is `5`.
63+
- `heading`: Whether higher-level sections (h1 > h2 > h3) rank higher. Default is `true`.
64+
- `snippet`: Return highlighted text excerpts.
65+
- `columns`: Which columns to snippet (`['title']`, `['content']`, or both). Default is `['content']`.
66+
- `around`: Number of tokens around the match. Default is `30`.
67+
- `tag`: HTML tag for highlighting. Default is `'mark'`.
68+
- `init()`: Manually trigger index building. Useful when `immediate: false`.
69+
70+
### Result Type
71+
72+
```ts
73+
interface SearchResult {
74+
collection: string
75+
id: string
76+
title: string
77+
titles: string[]
78+
level: number
79+
content: string
80+
rank: number
81+
snippets?: { title?: string, content?: string }
82+
}
83+
```
84+
85+
## Examples
86+
87+
### Basic Search
88+
89+
```vue [SearchPage.vue]
90+
<script setup lang="ts">
91+
const { status, search } = useSearchCollection('docs')
92+
93+
const query = ref('')
94+
const results = ref([])
95+
96+
async function onSearch() {
97+
results.value = query.value
98+
? await search(query.value, { limit: 20 })
99+
: []
100+
}
101+
</script>
102+
103+
<template>
104+
<UInput v-model="query" :disabled="status !== 'ready'" @input="onSearch" />
105+
<ul>
106+
<li v-for="result in results" :key="result.id">
107+
<NuxtLink :to="result.id">{{ result.title }}</NuxtLink>
108+
</li>
109+
</ul>
110+
</template>
111+
```
112+
113+
### Multi-Collection Search
114+
115+
```vue [GlobalSearch.vue]
116+
<script setup lang="ts">
117+
const { status, search } = useSearchCollection(['docs', 'blog'])
118+
119+
const results = ref([])
120+
const query = ref('')
121+
122+
watch(query, async (value) => {
123+
results.value = value
124+
? await search(value, {
125+
limit: 20,
126+
snippet: { columns: ['content'], around: 40 },
127+
})
128+
: []
129+
})
130+
</script>
131+
```
132+
133+
### Deferred Initialization
134+
135+
```vue [LazySearch.vue]
136+
<script setup lang="ts">
137+
const { status, search, init } = useSearchCollection('docs', {
138+
immediate: false,
139+
})
140+
141+
async function onFocus() {
142+
if (status.value === 'idle') {
143+
await init()
144+
}
145+
}
146+
</script>
147+
```
148+
149+
### Reactive Collections
150+
151+
```vue [VersionedSearch.vue]
152+
<script setup lang="ts">
153+
const version = ref('v4')
154+
const collection = computed(() => `nuxt-${version.value}`)
155+
156+
const { status, search } = useSearchCollection(collection)
157+
</script>
158+
159+
<template>
160+
<select v-model="version">
161+
<option>v3</option>
162+
<option>v4</option>
163+
<option>v5</option>
164+
</select>
165+
</template>
166+
```
167+
168+
When the collection value changes, the FTS index is dropped and rebuilt for the new collections.
169+
170+
## Compared to queryCollectionSearchSections
171+
172+
| | `useSearchCollection` | `queryCollectionSearchSections` + Fuse.js |
173+
|---|---|---|
174+
| **Dependencies** | None (built-in FTS5) | Requires external library |
175+
| **Index** | SQLite inverted index | In-memory JS scan |
176+
| **Speed** | O(log n) indexed lookup | O(n) per query |
177+
| **Snippets** | Built-in | Manual |
178+
| **Typo tolerance** | Prefix only | Full fuzzy (edit distance) |
179+
| **Multi-collection** | Native | Manual merging |
180+
181+
Use `useSearchCollection` when you need fast, zero-dependency search. Use `queryCollectionSearchSections` with Fuse.js or MiniSearch when you need typo-tolerant fuzzy matching.

‎docs/content/docs/8.advanced/1.fulltext-search.md‎

Lines changed: 59 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,47 @@
11
---
22
title: Full-Text Search
3-
description: Implement full-text search in your website using Nuxt Content
3+
description: Implement full-text search in your website using Nuxt Content.
44
---
55

6-
Content module exposes a handy utility [`queryCollectionSearchSections`](/docs/utils/query-collection-search-sections) to break down content files into searchable sections. This is useful for implementing full-text search in your website. You can use the result of this utility in combination with [Nuxt UI Content Search](https://ui.nuxt.com/pro/components/content-search) or other search libraries like [Fuse.js](https://fusejs.io/), [minisearch](https://lucaong.github.io/minisearch), etc.
6+
## Built-in FTS5 Search
77

8-
## Nuxt UI
9-
10-
Nuxt UI provides a ready to use component for full-text search. You can use it by passing the result of `queryCollectionSearchSections` to the `files` prop of the component.
11-
12-
Read more about [Nuxt UI Content Search](https://ui.nuxt.com/pro/components/content-search).
8+
Content module provides [`useSearchCollection`](/docs/utils/use-search-collection), a zero-dependency composable powered by SQLite FTS5. It builds an inverted index from your content sections and provides instant ranked search with prefix matching and snippets.
139

14-
::code-group
15-
```vue [UContentSearchExample.vue]
10+
```vue [SearchExample.vue]
1611
<script setup lang="ts">
17-
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('docs'))
18-
const { data: files } = await useAsyncData('search', () => queryCollectionSearchSections('docs'))
12+
const { status, search } = useSearchCollection('docs')
13+
const query = ref('')
14+
const results = ref([])
1915
20-
const searchTerm = ref('')
16+
watch(query, async (value) => {
17+
results.value = value
18+
? await search(value, { snippet: { columns: ['content'], around: 40 } })
19+
: []
20+
})
2121
</script>
2222
2323
<template>
24-
<UContentSearch
25-
v-model:search-term="searchTerm"
26-
:files="files"
27-
:navigation="navigation"
28-
:fuse="{ resultLimit: 42 }"
29-
/>
24+
<UInput v-model="query" :disabled="status !== 'ready'" placeholder="Search..." />
25+
<ul>
26+
<li v-for="result in results" :key="result.id">
27+
<NuxtLink :to="result.id">{{ result.title }}</NuxtLink>
28+
<p v-if="result.snippets?.content" v-html="result.snippets.content" />
29+
</li>
30+
</ul>
3031
</template>
3132
```
3233

33-
:::code-preview{label="Preview" icon="i-lucide-eye"}
34-
::::example-fulltext-content-search
35-
::::
36-
:::
34+
::tip{to="/docs/utils/use-search-collection"}
35+
Read more about `useSearchCollection` composable.
3736
::
3837

39-
## MiniSearch example
38+
## External Libraries
39+
40+
You can also use [`queryCollectionSearchSections`](/docs/utils/query-collection-search-sections) to get raw section data and pass it to search libraries like [Fuse.js](https://fusejs.io/) or [MiniSearch](https://lucaong.github.io/minisearch). This approach gives you typo-tolerant fuzzy matching at the cost of loading all sections into memory.
41+
42+
### MiniSearch
4043

41-
Read more about [minisearch](https://lucaong.github.io/minisearch).
44+
[MiniSearch](https://lucaong.github.io/minisearch) is a lightweight full-text search library with prefix matching, fuzzy search, and field boosting.
4245

4346
::code-group
4447
```vue [MiniSearchExample.vue]
@@ -83,12 +86,12 @@ const result = computed(() => miniSearch.search(toValue(query)))
8386
:::
8487
::
8588

86-
## Fuse.js example
89+
### Fuse.js
8790

88-
Read more about [Fuse.js](https://fusejs.io).
91+
[Fuse.js](https://fusejs.io) is a fuzzy search library that uses the Bitap algorithm for typo-tolerant matching with configurable thresholds.
8992

9093
::code-group
91-
```vue [FusejsExample.vue]
94+
```vue [FuseJSExample.vue]
9295
<script setup lang="ts">
9396
import Fuse from 'fuse.js'
9497
@@ -126,3 +129,32 @@ const result = computed(() => fuse.search(toValue(query)).slice(0, 10))
126129
::::
127130
:::
128131
::
132+
133+
## Nuxt UI
134+
135+
Nuxt UI provides a [ContentSearch](https://ui.nuxt.com/components/content-search) component that is powered by `fuse.js` and accepts the output of `queryCollectionSearchSections` directly.
136+
137+
::code-group
138+
```vue [ContentSearchExample.vue]
139+
<script setup lang="ts">
140+
const { data: navigation } = await useAsyncData('navigation', () => queryCollectionNavigation('docs'))
141+
const { data: files } = await useAsyncData('search', () => queryCollectionSearchSections('docs'))
142+
143+
const searchTerm = ref('')
144+
</script>
145+
146+
<template>
147+
<UContentSearch
148+
v-model:search-term="searchTerm"
149+
:files="files"
150+
:navigation="navigation"
151+
:fuse="{ resultLimit: 42 }"
152+
/>
153+
</template>
154+
```
155+
156+
:::code-preview{label="Preview" icon="i-lucide-eye"}
157+
::::example-fulltext-content-search
158+
::::
159+
:::
160+
::

‎docs/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"@vueuse/nuxt": "^14.2.1",
1515
"better-sqlite3": "^12.8.0",
1616
"docus": "^5.8.1",
17+
"drizzle-kit": "^0.31.10",
1718
"drizzle-orm": "^0.45.1",
1819
"minisearch": "^7.2.0",
1920
"nuxt": "^4.4.2",

‎playground/app.vue‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ const items = ref([
4040
icon: 'i-lucide-folder-open',
4141
to: '/data/foo',
4242
},
43+
{
44+
label: 'Search',
45+
icon: 'i-lucide-search',
46+
to: '/search',
47+
},
4348
])
4449
</script>
4550

‎playground/content.config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,17 @@ const collections = {
128128
prefix: '/vue',
129129
},
130130
}),
131+
ui: defineCollection({
132+
type: 'page',
133+
source: {
134+
repository: {
135+
url: 'https://github.com/nuxt/ui',
136+
branch: 'v4',
137+
},
138+
include: 'docs/content/**/*.md',
139+
prefix: '',
140+
},
141+
}),
131142
}
132143

133144
export default defineContentConfig({ collections })

‎playground/nuxt.config.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
export default defineNuxtConfig({
22
modules: [
33
'@nuxt/ui',
4-
'@nuxthub/core',
54
'@nuxt/content',
65
'nuxt-llms',
76
],
@@ -38,11 +37,6 @@ export default defineNuxtConfig({
3837
},
3938
},
4039
compatibilityDate: '2025-10-15',
41-
hub: {
42-
db: 'sqlite',
43-
// Or use PGlite with NuxtHub:
44-
// db: 'postgresql',
45-
},
4640
llms: {
4741
domain: 'http://localhost:3000',
4842
title: 'Content Playground',

‎playground/package.json‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,10 @@
99
"dev:prepare": "nuxt prepare"
1010
},
1111
"devDependencies": {
12-
"@electric-sql/pglite": "^0.4.2",
13-
"@libsql/client": "^0.17.2",
1412
"@nuxt/content": "latest",
1513
"@nuxt/ui": "^4.6.0",
16-
"@nuxthub/core": "^0.10.7",
17-
"better-sqlite3": "^12.8.0",
18-
"drizzle-orm": "^0.45.1",
1914
"nuxt": "^4.4.2",
2015
"nuxt-llms": "^0.2.0",
21-
"pg": "^8.20.0",
2216
"remark-code-import": "^1.2.0",
2317
"shiki-transformer-color-highlight": "^1.1.0"
2418
}

0 commit comments

Comments
 (0)