> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 搜尋

> Laravel 搜尋功能全景。說明如何依用途分別使用全文檢索、向量搜尋、rerank 與 Laravel Scout。

## 前言

為應用程式加入搜尋功能有多種方式，取決於用途。Laravel 提供從關鍵字比對到使用 AI 的語意搜尋，無需外部服務即可運作的內建工具。

```mermaid theme={null}
flowchart TD
    Q["搜尋需求"]
    Q --> A{"關鍵字比對是否已足夠？"}
    A -->|Yes| B["全文檢索<br>whereFullText"]
    A -->|No - 想以語意比對| C["向量搜尋<br>whereVectorSimilarTo"]
    Q --> D{"是否需要 model 自動同步？"}
    D -->|Yes| E["Laravel Scout<br>Searchable trait"]
    Q --> F{"是否用 AI 重新排序結果的關聯度？"}
    F -->|Yes| G["Reranking<br>AI SDK Reranking"]
```

### 功能比較

| 功能                     | 外部服務                       | 特徵                                   |
| ---------------------- | -------------------------- | ------------------------------------ |
| `whereFullText`        | 不需要                        | MariaDB / MySQL / PostgreSQL 內建的全文索引 |
| `whereVectorSimilarTo` | 不需要（PostgreSQL + pgvector） | 以語意相似度搜尋。需要 AI SDK                   |
| `Reranking`            | AI 供應商                     | 對任意結果集以 AI 依關聯度重新排序                  |
| Laravel Scout          | 不需要（database 引擎）／任意        | Eloquent model 的自動索引同步               |

***

## 全文檢索

`LIKE` 查詢對簡單的部分比對很方便，但不理解語言。全文檢索使用專用索引，考量單詞邊界、語形變化與關聯度分數進行搜尋。

MariaDB、MySQL、PostgreSQL 都內建支援全文檢索，不需要外部服務。

<Warning>
  全文檢索由 MariaDB、MySQL、PostgreSQL 支援。
</Warning>

### 加入全文索引

要使用全文檢索，先為目標欄位加上全文索引。

```php theme={null}
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();

    $table->fullText(['title', 'body']); // 複合索引
});
```

PostgreSQL 可為索引指定語言設定。英文以外的語言，語形變化處理會不同。

```php theme={null}
$table->fullText('body')->language('english');
```

索引的細節請參閱[Migration](/zh-TW/migrations)。

<Info>
  **中文全文檢索的注意事項**\
  MySQL 對中文全文檢索的處理較不友善。中文與日文一樣，多需搭配專用分詞器。如 AWS RDS 上僅可使用 N-gram parser，無法加入形態解析外掛。Laravel Cloud 的 MySQL 也是類似情況。PostgreSQL 對中文語形變化支援亦有限。若中文搜尋準確度重要，可考慮使用 Meilisearch 或 Typesense 等專用引擎。
</Info>

### 執行全文查詢

加入索引後，用 `whereFullText` 方法搜尋。Laravel 會依所使用的資料庫 driver 產生合適的 SQL（MariaDB / MySQL 為 `MATCH(...) AGAINST(...)`，PostgreSQL 為 `to_tsvector(...) @@ plainto_tsquery(...)`）。

```php theme={null}
$articles = Article::whereFullText('body', 'web developer')->get();
```

若建立了複合索引，就傳入相同的欄位陣列。

```php theme={null}
$articles = Article::whereFullText(
    ['title', 'body'], 'web developer'
)->get();
```

<Info>
  MariaDB、MySQL 中結果會自動依關聯度分數排序。而 PostgreSQL 的 `whereFullText` 只是過濾符合的記錄，並不會依關聯度排序。若在 PostgreSQL 希望自動關聯度排序，可用 [Scout 的資料庫引擎](#laravel-scout)。
</Info>

`orWhereFullText` 方法可以以 OR 條件加入全文檢索。詳細請參閱[查詢建構器文件](/zh-TW/query-builder)。

***

## 語意／向量搜尋

全文檢索依賴關鍵字的比對。向量搜尋採取根本不同的做法，將 AI 產生的向量嵌入視為文字*語意*的數值陣列，搜尋語意上相近的結果。

例如以「best wineries in Napa Valley」搜尋時，可以命中標題為「Top Vineyards to Visit」的文章。即使單詞不同，語意相近。

<Note>
  向量搜尋需要 [Laravel AI SDK](/zh-TW/ai-sdk)，支援 PostgreSQL（需 `pgvector` extension）與 MongoDB（需 Laravel MongoDB 套件）。[Laravel Cloud](https://laravel.com/cloud) 所有 Postgres 資料庫都已預裝 `pgvector`。
</Note>

### 產生嵌入

嵌入是表達文字語意的高維數值陣列（通常數百至數千維）。可用 Laravel 的 `Stringable` 類別的 `toEmbeddings` 方法產生。

```php theme={null}
use Illuminate\Support\Str;

$embedding = Str::of('Napa Valley has great wine.')->toEmbeddings();
```

一次處理多段文字時，使用 `Embeddings` 類別更有效率（可用一次 API 呼叫）。

```php theme={null}
use Laravel\Ai\Embeddings;

$response = Embeddings::for([
    'Napa Valley has great wine.',
    'Laravel is a PHP framework.',
])->generate();

$response->embeddings; // [[0.123, 0.456, ...], [0.789, 0.012, ...]]
```

嵌入供應商設定與維度自訂請參閱 [AI SDK 文件](/zh-TW/ai-sdk)。

### 向量的儲存與索引建立

要儲存向量嵌入，在 migration 定義 `vector` 欄位。依嵌入供應商的輸出維度指定 `dimensions`（如 OpenAI 的 `text-embedding-3-small` 為 1536 維）。呼叫 `index()` 建立 HNSW 索引，可大幅加速大型資料集的相似搜尋。

```php theme={null}
Schema::ensureVectorExtensionExists(); // 啟用 pgvector extension

Schema::create('documents', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->vector('embedding', dimensions: 1536)->index();
    $table->timestamps();
});
```

在 Eloquent model 將 `embedding` 欄位 cast 為 `array`，自動處理 PHP 陣列與資料庫向量格式的轉換。

```php theme={null}
protected function casts(): array
{
    return [
        'embedding' => 'array',
    ];
}
```

向量欄位與索引細節請參閱[Migration](/zh-TW/migrations)。

### 以相似度搜尋

儲存嵌入後，可用 `whereVectorSimilarTo` 方法搜尋相似記錄。使用 cosine similarity 比較向量，過濾掉 `minSimilarity` 門檻以下的結果，並依關聯度高至低自動排序。門檻為 `0.0`〜`1.0`，`1.0` 表示完全相符。

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
    ->limit(10)
    ->get();
```

除傳入嵌入陣列外，也可傳入字串，Laravel 會自動產生嵌入。可以直接傳入使用者查詢字串，非常方便。

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', 'best wineries in Napa Valley')
    ->limit(10)
    ->get();
```

若需要更細緻的控制，可使用 `whereVectorDistanceLessThan`、`selectVectorDistance`、`orderByVectorDistance`。詳情請參閱[查詢建構器文件](/zh-TW/query-builder)與 [AI SDK 文件](/zh-TW/ai-sdk)。

***

## Reranking

Reranking 是 AI 模型將結果集依查詢的關聯度重新排序的方法。與向量搜尋不同，不需事先計算或儲存嵌入，可套用於任意文字集合。

先用全文檢索快速篩出大量記錄，再套用 rerank 的「**搜尋→重排**」模式尤其有效。可兼顧資料庫速度與 AI 精度。

```php theme={null}
use Laravel\Ai\Reranking;

$response = Reranking::of([
    'Django is a Python web framework.',
    'Laravel is a PHP web application framework.',
    'React is a JavaScript library for building user interfaces.',
])->rerank('PHP frameworks');

$response->first()->document; // "Laravel is a PHP web application framework."
```

Laravel collection 提供 `rerank` macro，只要傳入欄位名稱（或 closure）與查詢就能對 Eloquent 結果重排。

```php theme={null}
$articles = Article::all()
    ->rerank('body', 'Laravel tutorials');
```

Rerank 供應商設定與可用選項請參閱 [AI SDK 文件](/zh-TW/ai-sdk)。

***

## Laravel Scout

前述搜尋方法都是直接呼叫查詢建構器的方法。[Laravel Scout](/zh-TW/scout) 採取不同做法：在 Eloquent model 加入 `Searchable` trait，Scout 就會依記錄的建立、更新、刪除自動同步搜尋索引。

### 資料庫引擎

Scout 內建的資料庫引擎會對既有資料庫進行全文檢索與 `LIKE` 搜尋，無需外部服務或額外基礎架構。

以 `toSearchableArray` 方法定義搜尋對象欄位。可用 PHP 屬性為每欄指定搜尋策略。

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    #[SearchUsingPrefix(['id'])]
    #[SearchUsingFullText(['title', 'body'])]
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
        ];
    }
}
```

| 屬性                    | 搜尋策略                                      |
| --------------------- | ----------------------------------------- |
| `SearchUsingFullText` | 使用全文索引（`MATCH...AGAINST` / `to_tsvector`） |
| `SearchUsingPrefix`   | 前綴相符（`example%`）                          |
| 無                     | 前後萬用字元（`%example%`）                       |

<Warning>
  指定 `SearchUsingFullText` 的欄位需事先建立[全文索引](/zh-TW/migrations)。
</Warning>

加上 trait 後，可用 `search` 方法搜尋 model。Scout 的資料庫引擎在 PostgreSQL 也會自動回傳依關聯度排序的結果。

```php theme={null}
$articles = Article::search('Laravel')->get();
```

### 第三方引擎

Scout 也支援 [Algolia](https://www.algolia.com/)、[Meilisearch](https://www.meilisearch.com)、[Typesense](https://typesense.org) 等第三方搜尋引擎。這些提供拼字容錯、多面向搜尋、地理搜尋、自訂排名等進階功能。

Scout 提供統一 API，之後從資料庫引擎遷移到第三方引擎時，程式碼變動極小。

<Note>
  多數應用程式並不需要外部搜尋引擎。本頁介紹的內建做法可涵蓋大多數情境。
</Note>

Scout 的細節請參閱 [Laravel Scout 指南](/zh-TW/scout)。

***

## 技術組合

前述搜尋方法並非互斥。組合使用可獲得最佳結果。

### 全文檢索 + Reranking

用全文檢索快速篩出候選，再用 Reranking 依語意關聯度重排。是同時兼顧資料庫速度與 AI 精度的模式。

```php theme={null}
$articles = Article::query()
    ->whereFullText('body', $request->input('query'))
    ->limit(50)
    ->get()
    ->rerank('body', $request->input('query'), limit: 10);
```

### 向量搜尋 + 一般過濾

結合向量相似搜尋與一般 `where` 子句，實現對特定子集的語意搜尋。適用於在依團隊或分類篩選同時進行語意搜尋。

```php theme={null}
$documents = Document::query()
    ->where('team_id', $user->team_id)
    ->whereVectorSimilarTo('embedding', $request->input('query'))
    ->limit(10)
    ->get();
```

***

## 相關頁面

<Card title="Laravel Scout" icon="magnifying-glass" href="/zh-TW/scout">
  以 Searchable trait 自動同步 model 索引的完整指南。
</Card>

<Card title="Laravel AI SDK" icon="sparkles" href="/zh-TW/ai-sdk">
  向量嵌入與 rerank 所需 AI SDK 的設定方式。
</Card>

<Card title="查詢建構器" icon="database" href="/zh-TW/query-builder">
  whereFullText、whereVectorSimilarTo 等查詢建構器方法的細節。
</Card>

<Card title="Migration" icon="table" href="/zh-TW/migrations">
  全文索引與向量欄位的建立方式。
</Card>


## Related topics

- [Laravel Scout](/zh-TW/scout.md)
- [Basic client - Laravel Bluesky](/zh-TW/packages/laravel-bluesky/basic-client.md)
- [Laravel AI SDK](/zh-TW/ai-sdk.md)
- [MongoDB](/zh-TW/mongodb.md)
- [2026 年 3 月 Laravel 更新](/zh-TW/blog/changelog/202603.md)
