# 用 Next.js 和 Transformers.js 构建语义搜索引擎

URL: https://byshahid.com/zh/engineering/semantic-search-nextjs-transformers-js/
Author: Muhammad Shahid, Senior AI Software Engineer & Full Stack Developer (https://byshahid.com/)
Published: 2026-11-12

**快速解答:** 要用 Transformers.js 在 Next.js 中实现语义搜索，先在构建时用 all-MiniLM-L6-v2 这样的小模型把文档向量化一次，并把向量作为静态 JSON 文件发布。在浏览器中，Web Worker 用 Transformers.js 加载同一个模型，只对访客的查询做向量化，并按余弦相似度给文档排序；模型下载期间先返回关键词（BM25）结果。在本站 67 个工具上，它在 30 个普通英文问题中有 25 个把正确工具排在第一，关键词搜索只有 16 个；每次搜索 9 到 41 毫秒，不需要服务器。

- **技术栈:** Next.js 15 静态导出、Transformers.js 4、all-MiniLM-L6-v2（q8）、Web Worker
- **准确率:** 正确工具排第一：语义 25/30，关键词 16/30，等权混合 20/30
- **速度:** 首次访问首个结果 0.26 秒，模型 8.2 秒就绪（23 MB）；缓存后 0.58 秒；每次搜索 9 到 41 毫秒
- **索引:** 67 篇文档，int8 向量：48 KB，gzip 后 27 KB
- **语言:** 西班牙语问题：多语言模型 10/10 进入前三，英文模型 5/10

一个能理解 "make my pdf smaller for email" 并找到 PDF 压缩工具的搜索框，不需要搜索服务器、API 密钥，也没有按查询计费：这就是**浏览器内语义搜索**带来的。本教程用 **Next.js 和 Transformers.js** 来构建它，以本站 67 个免费工具作为文档，并且通过测量而不是假设来回答问题：正确工具排在第一的频率比关键词搜索高多少、两者混合是否有帮助、它如何处理其他语言的问题，以及在真实浏览器中需要多长时间。所有代码完整、通过类型检查，并以 Next.js 静态导出构建；准确率数字来自 Node.js 中的真实向量，耗时来自由 Playwright 驱动的 Google Chrome。

## 什么是语义搜索，为什么在浏览器中运行？

**语义搜索**按含义而不是共同的词来给文档排序。一个小型语言模型把每篇文档和每个查询转换成向量，也就是一串数字，含义相近的文本得到相近的向量；最接近的向量就是最佳匹配。关键词搜索只有在访客输入 "compress" 时才能匹配 "compress"；语义搜索还能匹配 "smaller"、"shrink" 和 "reduce the size"。用 **Transformers.js** 在浏览器中运行意味着无需托管搜索服务器，没有按查询计费，访客输入的内容也不会离开设备。代价是一次性的模型下载，本方案用即时的关键词结果把它掩盖起来。

## 设计

![设计：构建时一个 Node 脚本通过 Transformers.js 用 all-MiniLM-L6-v2 对 67 篇文档做向量化，写出包含 int8 向量的 search-index.json，48 KB，gzip 后 27 KB；在浏览器中，Next.js 页面与一个 Web Worker 通信，Worker 先用 BM25 关键词搜索即时回答，从 Hugging Face 下载一次 23 MB 的模型，然后对查询做向量化并在 9 到 41 毫秒内与 67 个向量比较](https://byshahid.com/blog/img/engineering/semantic-search-nextjs-transformers-js/architecture.svg)

*文档在构建时只向量化一次；浏览器中只对查询做向量化。*

两个决定让它变快。第一，文档向量在构建时计算一次，作为小型静态文件发布，所以浏览器只需要对查询做向量化。第二，所有模型工作都在 **Web Worker** 中进行，加载和向量化永远不会阻塞输入；在模型就绪前，Worker 用关键词搜索作答。

## 需要准备什么？

| 工具 | 使用版本 | 用途 |
| --- | --- | --- |
| Next.js | 15，静态导出 | 页面；任何静态托管都能提供服务 |
| @huggingface/transformers | 4 | 在 Node 和浏览器中运行向量模型 |
| all-MiniLM-L6-v2 | q8（8 位）权重 | 384 维向量，下载约 23 MB |
| TypeScript | 6 | Next.js 15 需要 TypeScript 6，尚不支持 TypeScript 7 |
| tsx | 任意版本 | 运行构建时的索引脚本 |

## 步骤 1：创建项目

```bash
npx create-next-app@15 tool-search --ts --app --no-tailwind --no-eslint && cd tool-search
npm install @huggingface/transformers
npm install -D tsx
```

```js
/** @type {import('next').NextConfig} */
export default { output: "export" };
```

`output: "export"` 让 `next build` 把普通的 HTML、JavaScript 和索引文件写入 `out/`，所以搜索可以在任何静态托管上运行，完全不需要服务器。

## 步骤 2：搜索代码

```ts
// Search logic shared by the build script, the browser worker and the tests. No dependencies.

export interface Doc { slug: string; href: string; name: string; text: string }
export interface SearchIndex { model: string; dims: number; docs: Doc[]; vectors: string } // vectors: base64 int8, docs x dims

// ---- Semantic: int8 vectors (normalised floats x 127), compared with a dot product
export function quantize(v: Float32Array): Int8Array {
  return Int8Array.from(v, (x) => Math.max(-127, Math.min(127, Math.round(x * 127))));
}
export function decodeVectors(b64: string): Int8Array {
  const bin = atob(b64);
  return Int8Array.from(bin, (c) => (c.charCodeAt(0) << 24) >> 24);
}
export function encodeVectors(all: Int8Array): string {
  let s = "";
  for (const x of all) s += String.fromCharCode(x & 255);
  return btoa(s);
}
export function semanticScores(query: Float32Array, vectors: Int8Array, dims: number): number[] {
  const n = vectors.length / dims;
  return Array.from({ length: n }, (_, d) => {
    let dot = 0;
    for (let i = 0; i < dims; i++) dot += query[i] * vectors[d * dims + i];
    return dot / 127; // cosine similarity, since both sides are normalised
  });
}

// ---- Keyword: BM25 over name + text
const tokenize = (s: string) => s.toLowerCase().normalize("NFKC").match(/[\p{L}\p{N}]+/gu) ?? [];
export function bm25Scorer(docs: Doc[], k1 = 1.2, b = 0.75) {
  const toks = docs.map((d) => tokenize(d.name + " " + d.name + " " + d.text)); // the name counts twice
  const avg = toks.reduce((n, t) => n + t.length, 0) / toks.length;
  const df = new Map<string, number>();
  for (const t of toks) for (const w of new Set(t)) df.set(w, (df.get(w) ?? 0) + 1);
  return (query: string) => {
    const q = [...new Set(tokenize(query))];
    return toks.map((t) => {
      let score = 0;
      for (const w of q) {
        const f = t.filter((x) => x === w).length;
        if (!f) continue;
        const idf = Math.log(1 + (docs.length - df.get(w)! + 0.5) / (df.get(w)! + 0.5));
        score += (idf * f * (k1 + 1)) / (f + k1 * (1 - b + (b * t.length) / avg));
      }
      return score;
    });
  };
}

// ---- Hybrid: reciprocal rank fusion, which needs only the two rankings, not comparable scores
export const rank = (scores: number[]) => scores.map((s, i) => [s, i] as const).sort((a, b) => b[0] - a[0]).map(([, i]) => i);
// weights let the better signal count more; equal weights are the classic RRF.
export function rrf(rankings: number[][], weights = rankings.map(() => 1), k = 60): number[] {
  const total = new Map<number, number>();
  rankings.forEach((r, j) => r.forEach((doc, pos) => total.set(doc, (total.get(doc) ?? 0) + weights[j] / (k + pos + 1))));
  return [...total.entries()].sort((a, b) => b[1] - a[1]).map(([doc]) => doc);
}
```

这个文件没有任何依赖，在 Node、浏览器和测试中都能运行。向量以 **int8** 存储：每个数乘以 127 后取整，使索引比 32 位浮点小四倍。下面的测试检查了这样做的代价：30 个问题中，排名第一的结果与全精度向量完全相同。`bm25Scorer` 是经典的关键词排序，在模型加载期间使用。`rrf` 是倒数排名融合（reciprocal rank fusion），是混合两种排序的常用方法，保留在这里是因为测试要衡量混合是否真的有帮助。

## 步骤 3：在构建时对文档做向量化

```ts
// Build time: embed every document once and ship the vectors as a small static file.
import { readFileSync, writeFileSync } from "node:fs";
import { pipeline } from "@huggingface/transformers";
import { encodeVectors, quantize, type Doc, type SearchIndex } from "../lib/search";

export const MODEL = "Xenova/all-MiniLM-L6-v2";
const docs: Doc[] = JSON.parse(readFileSync("corpus.json", "utf8")).map(({ slug, href, name, text }: Doc) => ({ slug, href, name, text }));
const embed = await pipeline("feature-extraction", MODEL, { dtype: "q8" }); // same model and precision as the browser
const all = new Int8Array(docs.length * 384);
for (const [i, d] of docs.entries()) {
  const out = await embed(d.name + ". " + d.text, { pooling: "mean", normalize: true });
  all.set(quantize(out.data as Float32Array), i * 384);
}
const index: SearchIndex = { model: MODEL, dims: 384, docs, vectors: encodeVectors(all) };
writeFileSync("public/search-index.json", JSON.stringify(index));
console.log("indexed " + docs.length + " docs, " + JSON.stringify(index).length + " bytes");
```

脚本用浏览器将使用的同一个模型和同样的 8 位权重，对每篇文档的名称和描述做向量化。这一点很重要：不同模型、甚至不同精度产生的向量无法比较。在 `next build` 之前运行它（例如作为 `prebuild` 脚本），让索引始终与内容一致。67 篇文档只需几秒钟，写出 48 KB，gzip 后 27 KB。

## 步骤 4：Web Worker

```ts
// Runs in a Web Worker: downloading the model and embedding never block typing.
// Keyword (BM25) results answer at once; semantic results take over as soon as the model is ready.
import { pipeline, type FeatureExtractionPipeline } from "@huggingface/transformers";
import { bm25Scorer, decodeVectors, rank, semanticScores, type SearchIndex } from "../../lib/search";

const indexReady = fetch("/search-index.json").then((r) => r.json() as Promise<SearchIndex>);
const keyword = indexReady.then((index) => ({ index, bm25: bm25Scorer(index.docs) }));
let model: FeatureExtractionPipeline | null = null;

indexReady.then(async (index) => {
  const t0 = performance.now();
  model = await pipeline("feature-extraction", index.model, { dtype: "q8" }); // cached by the browser after the first visit
  self.postMessage({ modelReady: Math.round(performance.now() - t0) });
});
const vectors = indexReady.then((index) => decodeVectors(index.vectors));

self.onmessage = async (e: MessageEvent<{ id: number; query: string }>) => {
  const { id, query } = e.data;
  const { index, bm25 } = await keyword;
  const t0 = performance.now();
  let scores: number[];
  let mode: "semantic" | "keyword";
  if (model) {
    const q = (await model(query, { pooling: "mean", normalize: true })).data as Float32Array;
    scores = semanticScores(q, await vectors, index.dims);
    mode = "semantic";
  } else {
    scores = bm25(query); // the model is still downloading: answer with keywords instead of waiting
    mode = "keyword";
  }
  const order = rank(scores).slice(0, 5);
  const results = order.filter((i) => scores[i] > 0).map((i) => ({ ...index.docs[i], score: Number(scores[i].toFixed(2)) }));
  self.postMessage({ id, mode, results, ms: Math.round(performance.now() - t0) });
};
```

Worker 立即获取索引并构建关键词评分器，所以在模型还不存在时就能回答第一次搜索。模型下载同时开始；Transformers.js 把文件保存在浏览器的 Cache Storage 中，所以第二次访问时直接从磁盘加载。每条消息都带有 id，Worker 会报告是哪种模式作答，页面就能显示 "keyword" 或 "semantic"。得分为 0 的结果会被丢弃，所以没有匹配的关键词搜索不会显示随机工具。

## 步骤 5：搜索页面

```tsx
"use client";
import { useEffect, useRef, useState } from "react";
import type { Doc } from "../../lib/search";

type Result = Doc & { score: number };

export default function SearchPage() {
  const worker = useRef<Worker | null>(null);
  const latest = useRef(0);
  const [modelMs, setModelMs] = useState<number | null>(null);
  const [mode, setMode] = useState("");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<Result[]>([]);
  const [ms, setMs] = useState<number | null>(null);

  useEffect(() => {
    const w = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
    w.onmessage = (e) => {
      if ("modelReady" in e.data) return setModelMs(e.data.modelReady);
      if (e.data.id !== latest.current) return; // ignore answers to older keystrokes
      setResults(e.data.results);
      setMs(e.data.ms);
      setMode(e.data.mode);
    };
    worker.current = w;
    return () => w.terminate();
  }, []);

  useEffect(() => {
    if (query.trim().length < 3) return setResults([]);
    const id = ++latest.current;
    const t = setTimeout(() => worker.current?.postMessage({ id, query }), 150); // debounce typing
    return () => clearTimeout(t);
  }, [query]);

  return (
    <main>
      <h1>Find a tool</h1>
      <input
        aria-label="Describe what you want to do"
        placeholder="e.g. make my pdf smaller"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        style={{ width: "100%", boxSizing: "border-box", fontSize: 18, padding: 10 }}
      />
      <p role="status">
        {ms !== null ? mode + " search, " + ms + " ms, on your device. " : ""}
        {modelMs === null ? "Smart search is loading; keyword results until then." : "Smart search ready."}
      </p>
      <ol>
        {results.map((r) => (
          <li key={r.slug}>
            <a href={r.href}>{r.name}</a> <small>({r.score})</small>
            <div>{r.text}</div>
          </li>
        ))}
      </ol>
    </main>
  );
}
```

页面对输入做 150 毫秒防抖，并忽略不是针对最新查询的回答，所以对 "mak" 的慢回答不会覆盖对 "make my pdf" 的回答。`new Worker(new URL("./worker.ts", import.meta.url))` 是 Next.js 会打包成独立 Worker 文件的写法。状态行是 ARIA live 区域，屏幕阅读器能在结果变化时播报。

## 准确率如何？

```ts
// How people actually ask, labelled with the tool that answers. None of them uses the tool's name.
export const queries: [string, string][] = [
  ["make my pdf file smaller for email", "compress-pdf"],
  ["join two pdfs into one", "merge-pdf"],
  ["turn a photo of a page into text I can copy", "image-to-text"],
  ["how long is my essay", "word-counter"],
  ["work out how old I am", "age-calculator"],
  ["shrink a picture without losing quality", "image-compressor"],
  // ...27 more, plus 10 Spanish questions and 10 short keyword searches
];
```

```ts
// Measures keyword, semantic and hybrid search on the labelled questions, and an English-only
// versus a multilingual model on Spanish questions. Real embeddings, run in Node.
import { readFileSync } from "node:fs";
import { pipeline } from "@huggingface/transformers";
import { bm25Scorer, decodeVectors, rank, rrf, semanticScores, type SearchIndex } from "../lib/search";
import { keywords, queries, spanish } from "./queries";

const index: SearchIndex = JSON.parse(readFileSync("public/search-index.json", "utf8"));
const vectors = decodeVectors(index.vectors);
const slugs = index.docs.map((d) => d.slug);
const bm25 = bm25Scorer(index.docs);

function report(label: string, rankings: number[][], wanted: string[]) {
  let hit1 = 0, hit3 = 0, mrr = 0;
  rankings.forEach((r, i) => {
    const pos = r.map((d) => slugs[d]).indexOf(wanted[i]);
    if (pos === 0) hit1++;
    if (pos >= 0 && pos < 3) hit3++;
    if (pos >= 0) mrr += 1 / (pos + 1);
  });
  const n = rankings.length;
  console.log(label.padEnd(34) + "top 1: " + String(hit1).padStart(2) + "/" + n + "   top 3: " + String(hit3).padStart(2) + "/" + n + "   MRR " + (mrr / n).toFixed(2));
}

const embed = await pipeline("feature-extraction", index.model, { dtype: "q8" });
// The query stays in float32; only the stored document vectors are int8.
const qv = async (q: string) => (await embed(q, { pooling: "mean", normalize: true })).data as Float32Array;

const kw = queries.map(([q]) => rank(bm25(q)));
const sem = await Promise.all(queries.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims))));
const hyb = kw.map((k, i) => rrf([k, sem[i]]));
console.log(queries.length + " English questions, " + index.docs.length + " tools");
report("keyword (BM25)", kw, queries.map((q) => q[1]));
report("semantic (MiniLM-L6, int8 docs)", sem, queries.map((q) => q[1]));
report("hybrid, equal weights (RRF)", hyb, queries.map((q) => q[1]));
for (const w of [2, 3, 5]) report("hybrid, semantic weighted x" + w, kw.map((k, i) => rrf([k, sem[i]], [1, w])), queries.map((q) => q[1]));

// Short keyword searches
const kKw = keywords.map(([q]) => rank(bm25(q)));
const kSem = await Promise.all(keywords.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims))));
console.log(keywords.length + " short keyword searches");
report("keyword (BM25)", kKw, keywords.map((q) => q[1]));
report("semantic (MiniLM-L6, int8 docs)", kSem, keywords.map((q) => q[1]));
report("hybrid, equal weights (RRF)", kKw.map((k, i) => rrf([k, kSem[i]])), keywords.map((q) => q[1]));
for (const w of [2, 3, 5]) report("hybrid, semantic weighted x" + w, kKw.map((k, i) => rrf([k, kSem[i]], [1, w])), keywords.map((q) => q[1]));

// Does int8 storage change the ranking? Compare with full-precision document vectors.
let same = 0;
const full = await Promise.all(index.docs.map(async (d) => (await embed(d.name + ". " + d.text, { pooling: "mean", normalize: true })).data as Float32Array));
for (const [i, [q]] of queries.entries()) {
  const v = await qv(q);
  const exact = rank(full.map((f) => f.reduce((s, x, j) => s + x * v[j], 0)));
  if (exact[0] === sem[i][0]) same++;
}
console.log("int8 vs float32 document vectors: same top result for " + same + "/" + queries.length + " questions");

// Spanish questions against English documents
console.log(spanish.length + " Spanish questions, English documents");
report("keyword (BM25)", spanish.map(([q]) => rank(bm25(q))), spanish.map((q) => q[1]));
report("semantic, English model", await Promise.all(spanish.map(async ([q]) => rank(semanticScores(await qv(q), vectors, index.dims)))), spanish.map((q) => q[1]));
const multi = await pipeline("feature-extraction", "Xenova/paraphrase-multilingual-MiniLM-L12-v2", { dtype: "q8" });
const mDocs = await Promise.all(index.docs.map(async (d) => (await multi(d.name + ". " + d.text, { pooling: "mean", normalize: true })).data as Float32Array));
const mRank = await Promise.all(spanish.map(async ([q]) => {
  const v = (await multi(q, { pooling: "mean", normalize: true })).data as Float32Array;
  return rank(mDocs.map((d) => d.reduce((s, x, j) => s + x * v[j], 0)));
}));
report("semantic, multilingual model", mRank, spanish.map((q) => q[1]));
```

```text
30 English questions, 67 tools
keyword (BM25)                    top 1: 16/30   top 3: 20/30   MRR 0.62
semantic (MiniLM-L6, int8 docs)   top 1: 25/30   top 3: 30/30   MRR 0.91
hybrid, equal weights (RRF)       top 1: 20/30   top 3: 24/30   MRR 0.76
hybrid, semantic weighted x2      top 1: 20/30   top 3: 26/30   MRR 0.79
hybrid, semantic weighted x3      top 1: 22/30   top 3: 27/30   MRR 0.84
hybrid, semantic weighted x5      top 1: 24/30   top 3: 29/30   MRR 0.88
10 short keyword searches
keyword (BM25)                    top 1:  8/10   top 3:  9/10   MRR 0.85
semantic (MiniLM-L6, int8 docs)   top 1:  9/10   top 3: 10/10   MRR 0.95
hybrid, equal weights (RRF)       top 1:  8/10   top 3:  9/10   MRR 0.86
hybrid, semantic weighted x2      top 1:  8/10   top 3:  9/10   MRR 0.87
hybrid, semantic weighted x3      top 1:  8/10   top 3: 10/10   MRR 0.88
hybrid, semantic weighted x5      top 1:  9/10   top 3: 10/10   MRR 0.95
int8 vs float32 document vectors: same top result for 30/30 questions
10 Spanish questions, English documents
keyword (BM25)                    top 1:  2/10   top 3:  3/10   MRR 0.29
semantic, English model           top 1:  2/10   top 3:  5/10   MRR 0.34
semantic, multilingual model      top 1:  6/10   top 3: 10/10   MRR 0.80
```

![首位准确率柱状图：在 30 个普通英文问题上，关键词 53%，语义 83%，等权混合 67%；在 10 个简短关键词搜索上，关键词 80%，语义 90%，混合 80%；在 10 个针对英文文档的西班牙语问题上，英文模型 20%，多语言模型 60%](https://byshahid.com/blog/img/engineering/semantic-search-nextjs-transformers-js/accuracy.svg)

*正确工具排在第一，问题由人工标注。*

这些问题按照人们实际提问的方式写成，不包含工具名称："how long is my essay"、"erase what is behind a person in a photo"。语义搜索在 30 个问题中有 25 个把正确工具排第一，全部 30 个都在前三；关键词搜索只得到 16 个第一。在 "jwt"、"bmi" 这类本应是关键词搜索强项的简短搜索中，语义搜索仍略胜一筹，10 个中 9 比 8。小模型对缩写的处理比预期好，因为文档中写出了它们的全称。

## 混合搜索：何时有帮助，何时有害

**混合搜索**，即混合关键词和语义排序，常被推荐为稳妥的默认选择，所以测试对它做了测量。等权混合反而让结果变差：20 个第一，而纯语义有 25 个，因为对普通语言的问题来说，关键词排序大多是噪声，而融合给了它与好排序同等的话语权。把语义权重提高到五倍后恢复到 24，仍不超过纯语义。当查询中含有模型没见过的罕见精确词，如产品代码、错误代码或人名时，混合搜索才划算；在这样的数据集上并没有。选择之前请在自己的问题上测量。本页面在模型加载后使用语义搜索，只在加载期间使用关键词搜索。

## 其他语言

all-MiniLM-L6-v2 是用英文训练的。用西班牙语提问、搜索英文文档时，它只有 2 个问题把正确工具排第一。多语言模型 `paraphrase-multilingual-MiniLM-L12-v2` 得到 6 个第一，10 个全部进入前三，因为它把不同语言中含义相同的句子映射到相近的向量。它的下载更大，所以当访客使用与文档不同的语言搜索时再使用它，并且要用同一个模型对文档做向量化。

## 速度如何？

```text
first visit: first result after 262 ms (keyword search: Compress PDF); smart search ready after 8248 ms; model downloaded 23.0 MB; sideways overflow 0px
  join two pdfs into one -> Merge PDF (41 ms)
  erase what is behind a person in a photo -> Background remover (16 ms)
  how far does a car go before it stops -> Stopping distance calculator (20 ms)
  unique id for a database row -> UUID generator (9 ms)
second visit (browser cache): first result after 573 ms (semantic search: Compress PDF); smart search ready after 578 ms; model downloaded 0.0 MB; sideways overflow 0px
  join two pdfs into one -> Merge PDF (10 ms)
  erase what is behind a person in a photo -> Background remover (12 ms)
  how far does a car go before it stops -> Stopping distance calculator (24 ms)
  unique id for a database row -> UUID generator (12 ms)
```

![在 Chrome 中测得的时间线：首次访问 0.26 秒出现关键词结果，在下载 23 MB 模型的同时，8.2 秒后语义搜索就绪；第二次访问从浏览器缓存加载，0.58 秒后语义搜索就绪；每次语义搜索耗时 9 到 41 毫秒](https://byshahid.com/blog/img/engineering/semantic-search-nextjs-transformers-js/timing.svg)

*首次访问只需为模型下载付出一次代价，之后搜索即时完成。*

首次访问时，第一个结果在 0.26 秒后出现，来自关键词搜索，同时 23 MB 的模型在下载；8.2 秒后语义搜索就绪。第二次访问时模型来自浏览器缓存，语义搜索 0.58 秒就绪。每次语义搜索耗时 9 到 41 毫秒。这些时间来自一台笔记本和家庭网络，在使用移动数据的手机上首次访问会更慢；关键词兜底能让搜索框在此期间依然可用。

## 让它更小更快

- **按需加载模型：**在访客聚焦搜索框时才开始下载，而不是每次浏览页面都下载，为从不搜索的人节省流量。

- **保持索引精简：**int8 向量每篇文档 384 字节；几千篇文档也只有大约 1 MB。

- **自托管模型文件**，放在自己的 CDN 上，如果你不希望访客的浏览器从 Hugging Face 下载。

- **在可用时使用 WebGPU** 运行更大的模型；对于这么小的模型，CPU 已经足够快。

## 常见错误及修复方法

| 错误 | 后果 | 修复 |
| --- | --- | --- |
| 文档和查询使用不同模型或精度 | 分数没有意义，结果看起来随机 | 构建时和浏览器中使用相同的模型和 dtype |
| 在浏览器中对所有文档做向量化 | 首次搜索慢，浪费电量 | 构建时向量化文档，发布向量 |
| 在主线程运行模型 | 模型加载时输入卡住 | 所有模型工作放在 Web Worker 中 |
| 等模型加载完才显示内容 | 慢速手机上搜索框空白好几秒 | 模型就绪前用关键词搜索作答 |
| 认为混合搜索总是更好 | 普通语言问题的结果变差 | 在自己的问题上分别测量 |
| 用英文模型处理其他语言 | 非英文查询匹配失败 | 两侧都使用多语言模型 |
| 内容变化后索引过期 | 新页面搜不到 | 在 prebuild 中重建索引 |

## 局限

测试集很小：30 个英文问题、10 个简短搜索和 10 个西班牙语问题，由一个人编写和标注，所以这些数字只是本站上各方法的比较，而不是通用准确率。客户端搜索适合几十到几千篇文档的集合；超过这个规模，索引和评分循环都会变大，向量数据库会是更好的工具。首次访问需要下载 23 MB，对部分使用移动数据的用户来说太多。小模型有时会把相近的结果排得很接近，所以展示三到五个结果，而不是一个。

## 什么时候改用服务器

当集合很大、是私有的或每分钟都在变化，或者需要筛选、按用户权限和查询分析时，就把搜索放到服务器上。同样的思路可以用向量数据库实现：参见 [基于 pgvector 的 RAG 流水线](/zh/engineering/nextjs-rag-pipeline-pgvector/)和 [MongoDB Atlas 与 pgvector 对比](/zh/engineering/mongodb-atlas-vector-search-vs-pgvector/)。同一个小型向量模型也用于[用 Redis 降低 LLM 成本指南](/zh/engineering/llm-token-costs-redis-caching-nextjs/)中的语义缓存。本文搜索的文档可以在[免费工具页面](/zh/tools/)看到。

## 常见问题

### 可以完全在浏览器中运行语义搜索吗？

可以。Transformers.js 能在浏览器中运行 all-MiniLM-L6-v2 等向量模型，所以可以在设备上对查询做向量化，并与作为静态文件发布的文档向量比较，不需要服务器。

### 模型下载有多大？

测试中，8 位权重的 all-MiniLM-L6-v2 下载了 23 MB。浏览器会缓存它，第二次访问 0.58 秒就加载完成。

### 应该在浏览器中对文档做向量化吗？

不应该。在构建时用相同的模型和精度向量化一次并发布向量，浏览器只需对查询做向量化。

### 客户端语义搜索有多快？

测试中在笔记本上对 67 篇文档每次搜索耗时 9 到 41 毫秒，运行在 Web Worker 中，所以输入不会卡顿。

### 语义搜索比关键词搜索好吗？

对普通语言问题好得多：测试中 30 个里有 25 个正确排第一，BM25 关键词搜索只有 16 个。在简短关键词搜索上也略好。

### 混合搜索总能改善结果吗？

不能。测试中关键词和语义等权混合得到 20/30，纯语义为 25/30。混合搜索主要在代码、名称等罕见精确词上有帮助。

### 如何在 Next.js 中使用 Transformers.js？

在用 new Worker(new URL("./worker.ts", import.meta.url)) 创建的 Web Worker 中加载它，在那里调用 pipeline("feature-extraction", model)，通过消息传递查询和结果。

### 语义搜索支持其他语言吗？

使用多语言模型就可以。对于搜索英文文档的西班牙语问题，paraphrase-multilingual-MiniLM-L12-v2 在 10 个问题中全部把正确工具排进前三，纯英文模型只有 5 个。

### int8 向量会损失准确率吗？

几乎不会。测试中 int8 文档向量的首位结果在 30 个问题上与全精度向量完全一致，体积只有四分之一。

### 模型下载期间搜索应该显示什么？

关键词结果。测试页面在 0.26 秒后用 BM25 作答，模型就绪后切换为语义搜索。

### 客户端搜索会把查询发送到服务器吗？

不会。查询在设备上向量化和比较。只有模型文件需要下载，而且只下载一次。

### 什么时候应该改用向量数据库？

当集合很大、私有或不断变化，或需要按用户权限和筛选时。客户端搜索适合几十到几千篇公开文档。

## 来源

- [Transformers.js documentation](https://huggingface.co/docs/transformers.js/index)
- [Hugging Face: Xenova/all-MiniLM-L6-v2](https://huggingface.co/Xenova/all-MiniLM-L6-v2)
- [Hugging Face: paraphrase-multilingual-MiniLM-L12-v2](https://huggingface.co/Xenova/paraphrase-multilingual-MiniLM-L12-v2)
- [Sentence Transformers (SBERT)](https://www.sbert.net/)
- [Next.js Docs: Static exports](https://nextjs.org/docs/app/guides/static-exports)
- [MDN: Web Workers API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)
- [Wikipedia: Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25)
- [Cormack, Clarke and Buettcher: Reciprocal rank fusion (SIGIR 2009)](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf)

查看相关服务: https://byshahid.com/zh/hire/ai-full-stack-developer/
