---
title: "useSearchCollection"
description: "useSearchCollection 组合式函数提供由 SQLite FTS5 支持的全文搜索，具备前缀匹配、BM25 排名和摘要片段功能。"
canonical_url: "https://nuxt-content.zhcndoc.com/docs/utils/use-search-collection"
---
# useSearchCollection

> useSearchCollection 组合式函数提供由 SQLite FTS5 支持的全文搜索，具备前缀匹配、BM25 排名和摘要片段功能。

## 用法

使用自动导入的 `useSearchCollection` 组合式函数在一个或多个集合中进行搜索。它会基于内容章节构建 FTS5 索引，并提供即时的排名搜索结果。

```vue [app.vue]
<script setup lang="ts">
const { status, search } = useSearchCollection('docs')

const query = ref('')
const results = ref([])

watch(query, async (value) => {
  results.value = value ? await search(value) : []
})
</script>
```

<note>

`useSearchCollection` 仅在客户端可用。FTS5 索引会在浏览器中使用 SQLite WASM 构建。

</note>

## Types

```ts
function useSearchCollection<T extends keyof PageCollections>(
  collection: MaybeRefOrGetter<T | T[]>,
  opts?: GenerateSearchSectionsOptions & { immediate?: boolean }
): {
  status: Ref<'idle' | 'loading' | 'ready' | 'error'>
  search: (query: string, opts?: SearchCollectionOptions) => Promise<SearchResult[]>
  init: () => Promise<DatabaseAdapter>
}
```

## API

### 参数

- `collection`：单个集合键、集合键数组，或响应式 ref/getter。值变化时，会为新的集合重建 FTS 索引。
- `opts`：（可选）构建索引选项：

  - `immediate`：是否立即开始构建索引。默认值为 `true`。设为 `false` 可延迟到第一次调用 `search()` 或显式调用 `init()` 时再执行。
  - `ignoredTags`：提取章节内容时要忽略的标签（例如 `['code']`）。
  - `minHeading`：拆分章节时使用的最小标题级别（例如 `'h2'`）。默认值为 `'h1'`。
  - `maxHeading`：拆分章节时使用的最大标题级别（例如 `'h4'`）。默认值为 `'h6'`。

### 返回值

- `status`：一个响应式 ref，表示索引状态：`'idle'`、`'loading'`、`'ready'` 或 `'error'`。
- `search(query, opts?)`：执行搜索查询。返回一个包含排序结果的 promise。

  - `query`：搜索字符串。自动支持前缀匹配（输入 `compo` 会匹配 "composable"）。
  - `opts`：（可选）搜索选项：
  
    - `limit`：最大结果数。默认值为 `20`。
    - `fields`：将搜索限制在特定列（`'title'` 或 `'content'`）。
    - `minTermLength`：跳过短于此值的词项。默认值为 `1`。
    - `weights`：控制排序行为。
    
      - `title`：标题匹配的提升因子。默认值为 `20`。
      - `content`：内容匹配的提升因子。默认值为 `5`。
      - `heading`：控制标题级别提升的指数（`0.5` = 平方根曲线，`1` = 线性，`0` = 禁用）。默认值为 `0.5`。
    - `snippet`：返回高亮文本摘录。
    
      - `columns`：对哪些列生成摘录（`['title']`、`['content']`，或两者都生成）。默认值为 `['content']`。
      - `around`：匹配项前后保留的 token 数。默认值为 `30`。
      - `tag`：用于高亮的 HTML 标签。默认值为 `'mark'`。
- `init()`：手动触发索引构建。在 `immediate: false` 时很有用。

### 结果类型

```ts
interface SearchResult {
  collection: string
  id: string
  title: string
  titles: string[]
  level: number
  content: string
  rank: number
  snippets?: { title?: string, content?: string }
}
```

## 示例

### 基本搜索

```vue [SearchPage.vue]
<script setup lang="ts">
const { status, search } = useSearchCollection('docs')

const query = ref('')
const results = ref([])

async function onSearch() {
  results.value = query.value
    ? await search(query.value, { limit: 20 })
    : []
}
</script>

<template>
  <UInput v-model="query" :disabled="status !== 'ready'" @input="onSearch" />
  <ul>
    <li v-for="result in results" :key="result.id">
      <NuxtLink :to="result.id">{{ result.title }}</NuxtLink>
    </li>
  </ul>
</template>
```

### 多集合搜索

```vue [GlobalSearch.vue]
<script setup lang="ts">
const { status, search } = useSearchCollection(['docs', 'blog'])

const results = ref([])
const query = ref('')

watch(query, async (value) => {
  results.value = value
    ? await search(value, {
        limit: 20,
        snippet: { columns: ['content'], around: 40 },
      })
    : []
})
</script>
```

### 延迟初始化

```vue [LazySearch.vue]
<script setup lang="ts">
const { status, search, init } = useSearchCollection('docs', {
  immediate: false,
})

async function onFocus() {
  if (status.value === 'idle') {
    await init()
  }
}
</script>
```

### 响应式集合

```vue [VersionedSearch.vue]
<script setup lang="ts">
const version = ref('v4')
const collection = computed(() => `nuxt-${version.value}`)

const { status, search } = useSearchCollection(collection)
</script>

<template>
  <select v-model="version">
    <option>v3</option>
    <option>v4</option>
    <option>v5</option>
  </select>
</template>
```

当集合值发生变化时，FTS 索引会被删除并为新集合重建。

## 与 queryCollectionSearchSections 的对比

<table>
<thead>
  <tr>
    <th>
      
    </th>
    
    <th>
      <code>
        useSearchCollection
      </code>
    </th>
    
    <th>
      <code>
        queryCollectionSearchSections
      </code>
      
       + Fuse.js
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <strong>
        依赖
      </strong>
    </td>
    
    <td>
      无（内置 FTS5）
    </td>
    
    <td>
      需要外部库
    </td>
  </tr>
  
  <tr>
    <td>
      <strong>
        索引
      </strong>
    </td>
    
    <td>
      SQLite 倒排索引
    </td>
    
    <td>
      内存中的 JS 扫描
    </td>
  </tr>
  
  <tr>
    <td>
      <strong>
        速度
      </strong>
    </td>
    
    <td>
      O(log n) 索引查找
    </td>
    
    <td>
      每次查询 O(n)
    </td>
  </tr>
  
  <tr>
    <td>
      <strong>
        摘要片段
      </strong>
    </td>
    
    <td>
      内置
    </td>
    
    <td>
      手动实现
    </td>
  </tr>
  
  <tr>
    <td>
      <strong>
        拼写容错
      </strong>
    </td>
    
    <td>
      仅前缀匹配
    </td>
    
    <td>
      完整模糊匹配（编辑距离）
    </td>
  </tr>
  
  <tr>
    <td>
      <strong>
        多集合
      </strong>
    </td>
    
    <td>
      原生支持
    </td>
    
    <td>
      手动合并
    </td>
  </tr>
</tbody>
</table>

当你需要快速、零依赖的搜索时，使用 `useSearchCollection`。当你需要容错拼写的模糊匹配时，使用带有 Fuse.js 或 MiniSearch 的 `queryCollectionSearchSections`。


## Sitemap

See the full [sitemap](https://nuxt-content.zhcndoc.com/sitemap.md) for all pages.
