---
title: Orama的再应用，替换Pagefind
tags:
  - astro
  - orama
  - 搜索
  - pagefind
  - 中文分词
categories:
  - 技术
date: 2026-11-20 12:29:46
desc: Stalux 再次把静态搜索从 Pagefind 换到 Orama。本文用两轮各 1,000 组查询对照中文命中率、召回和索引体积，解释为什么选择 PT15，以及如何让 Astro dev 和生产构建共用内容集合索引。
abbrlink: orama-again-replace-pagefind
cover: /images/orama-again-replace-pagefind/cover.webp
---
> **AI 辅助声明｜AI agent coding 辅助创作**

![文章转成索引卡片，放大镜照亮检索结果](/images/orama-again-replace-pagefind/cover.webp)

[上一次接入 Orama](https://xingwangzhe.fun/posts/orama-search-replace-pagefind/)之后，Stalux 又用过一段时间的 Pagefind。

这回我用博客语料做了两轮各 1,000 组查询，在 Stalux v1.66.0 换回 Orama，索引选了 PT15。

v1.70.0 把搜索配置和 WebMCP 迁到 Orama，v1.75.0 清掉了剩余的文章 HTML 标记和旧接口数据结构。

本文的配置示例使用 Stalux **v1.76.0**，该版本支持在 Astro 增量构建中复用 Orama 索引。

<!--more-->

## Pagefind 和 Orama

| 引擎 | 怎么建索引 | 可以改到哪一层 |
| --- | --- | --- |
| Pagefind | 扫描 HTML，或用 `addCustomRecord()` 直接传文本和元数据 | 调整正文范围、筛选、排序和排名权重 |
| Orama | 按 schema 写入字段，支持全文、向量和混合搜索 | 可以替换分词器、索引、排序等组件 |

[Pagefind Node.js API](https://pagefind.app/docs/node-api/) · [Orama 组件接口](https://docs.orama.com/docs/orama-js/internals/components)

```mermaid title="同一份内容生成两种静态索引"
flowchart TD
    A["259 条内容记录"] --> B["Pagefind 1.6.0"]
    A --> C["Orama 3.1.18 + PT15"]
    B --> D["addCustomRecord + getFiles"]
    C --> E["insert + persist + gzip"]
    D --> F["2.11 秒 · 分片共 3.16 MB"]
    E --> G["1.07 秒 · 单文件 3.19 MB"]
```

同一台 Ubuntu 电脑，各跑四次，取后三次的中位数。这里只计建索引和生成产物。Pagefind 可按需加载分片，图中体积是全部产物的总大小。

## 第一轮：从 Pagefind 到 Orama

```mermaid title="第一轮查询样本和评估流程"
flowchart TD
    A["固定种子 20261120<br/>1,000 个查询"] --> B["150 个单汉字 · 200 个中文词<br/>450 个中文子串 · 200 个技术词"]
    B --> C["Pagefind 同一 CJK 索引<br/>原样查询 / 查询端 bigram"]
    B --> D["Orama 的 BM25 索引<br/>全文 / 混合搜索"]
    B --> E["语料中的字面匹配<br/>作为预期结果"]
    C --> F["命中率、前十命中、准确率、召回率"]
    D --> F
    E --> F
```

| 方案 | 命中率 | 前十命中率 | 字面准确率 | 字面召回率 | 查询 P95 |
| --- | ---: | ---: | ---: | ---: | ---: |
| Pagefind 原样查询 | 98.8% | 81.7% | 45.58% | 95.97% | 7.20 ms |
| Pagefind 查询端中文 bigram | 98.4% | 79.3% | 41.91% | 95.87% | 7.59 ms |
| Orama 全文搜索（BM25） | 100% | 100% | 99.99% | 98.64% | 16.71 ms |
| Orama 混合搜索（BM25） | 100% | 100% | 99.99% | 98.64% | 17.24 ms |

命中率按查询计，准确率和召回率按全部返回结果与预期结果累计。Stalux 会复核原文字面命中，这也影响准确率。Pagefind 的本地查询 P95 更低，查询耗时不含下载和渲染。

## Stalux 开启了哪些能力

```mermaid title="同一个内容集合端点服务 dev 和 build"
flowchart TD
    A["已发布文章 · 关于 · 一言"] --> I{"开发请求或生产构建"}
    I -->|"astro dev 按需生成"| B["正文转纯文本<br/>提取元数据"]
    I -->|"astro build"| J{"增量构建缓存命中"}
    J -->|"命中"| F["/orama/index.bin"]
    J -->|"未命中或未开启"| B
    B --> C["Orama PT15"]
    C --> D["JSON 序列化 + gzip"]
    D --> F
    F --> G["Orama 官方搜索 UI"]
    F --> H["WebMCP 搜正文、读纯文本"]
```

端点源码节选，展示文章记录的映射。

```typescript title="orama-search-endpoint.ts · 文章记录"
const documents: SearchDocument[] = posts.map(({ data, rendered, body }) => {
    const post = String(data.abbrlink);
    return {
        url: sitePath(toRoutePath(`/posts/${post}`)),
        post,
        language,
        title: data.title,
        description: data.desc ?? "",
        // 正文没写 Astro，也可以从文章的 Astro 标签搜到
        keywords: [
            ...(data.tags ?? []),
            ...(data.categories ?? []),
            ...(data.searchKeywords ?? []),
        ].join(" "),
        content: searchablePostBody(rendered?.html, body),
        // 按站点时区解析发布时间
        published: toTimestamp(data.date, timezone),
        publishedDate: toMachineDateTime(data.date, timezone),
        category: data.categories?.[0] ?? "",
        tags: data.tags ?? [],
    };
});
```

| 开关或组件 | 现在的用法 |
| --- | --- |
| `orama` | 默认开启。设为 `false` 会关闭搜索入口、索引和 WebMCP 全文查询 |
| `orama.cjk` | 默认开启。使用 Mandarin tokenizer，并补充汉字单字和双字切分 |
| 全文和混合搜索 | 普通查询默认走混合模式，全文和向量权重分别为 0.85、0.15。向量来自本地词项特征哈希，无需下载模型 |
| `@orama/plugin-pt15` | 替换默认全文索引实现 |
| `@orama/plugin-data-persistence` | 序列化索引，再由 Stalux 做 gzip 压缩 |
| `@orama/wc-components` | 使用 Orama 官方搜索组件，接入 Stalux 的 i18n 和暗色模式，展示摘要高亮、时间、可点击的标签与分类 |

**v1.70.0 破坏性更新**。把 `pagefind` 改为 `orama`，把 `searchCjk` 移到 `orama.cjk`。 [Stalux v1.70.0 迁移指南](https://github.com/xingwangzhe/stalux/blob/v1.70.0/docs/SEARCH.md)

```typescript title="astro.config.ts · Orama 与增量构建"
import { defineConfig } from "astro/config";
import stalux from "@xingwangzhe/stalux";

export default defineConfig({
    experimental: { incrementalBuild: true }, // 可选，启用生产构建缓存
    integrations: [
        stalux({
            orama: { cjk: true }, // 也可省略，默认开启搜索和 CJK
            // orama: { cjk: false }, // 保留搜索，停用 CJK 分词与字符索引
            // orama: false, // 关闭搜索入口及全文索引
        }),
    ],
});
```

开启 `experimental.incrementalBuild` 后，构建会核对索引内容、相关配置和代码依赖，未变化时复用 `/orama/index.bin`。

在同一台机器用 myblog 副本做单轮热构建对照，总耗时从 **15.02 秒**降到 **13.71 秒**，编辑一篇文章后也验证了索引会重新生成。 [Stalux v1.76.0 索引实现](https://github.com/xingwangzhe/stalux/blob/v1.76.0/src/internal/orama-search-endpoint.ts)

| WebMCP 工具 | v1.76.0 行为 |
| --- | --- |
| `stalux_search_posts` | 从 `/orama/index.bin` 搜正文，全文成功时返回 `source: "orama+metadata"` |
| `stalux_read_post` | 优先读 Markdown。无可用 Markdown 时按文章 ID 从 Orama 索引读纯文本 |
| `orama: false` | 仍可查询元数据、读取已导出的 Markdown |

### v1.75.0 清理文章 DOM

WebMCP 现在直接读 Orama 的命中记录，文章 ID 从索引里的 `post` 字段取。

```typescript title="webmcp.ts · 按文章 ID 从索引读正文（节选）"
const [hit] = await orama.search("", id);
const record = hit?.document;
if (record?.post === id && typeof record.url === "string") {
    content = record.content;
    format = "text/plain";
    source = new URL(record.url, location.origin).href;
}
```

生产构建检查了 258 篇文章。仅移除旧文章 ID 属性，按属性长度计算，全站文章 HTML 合计少 **9,458 字节**，这个数字是压缩前的大小。 [Stalux v1.75.0](https://github.com/xingwangzhe/stalux/tree/v1.75.0)

查询端先把未通过字面匹配的候选去掉，再让最新发布的文章排在前面。以下是 Stalux 的结果处理节选。

```typescript title="orama-search.ts · 字面匹配和发布时间排序"
return hits
    .filter(({ document }) =>
        terms.every((word) =>
            searchableFields.some((field) =>
                normalizeSearch(document[field]).includes(word),
            ),
        ),
    )
    .sort((a, b) => b.document.published - a.document.published || b.score - a.score);
```

## 第二轮：QPS 和 PT15 怎么选

```mermaid title="同一批双词查询比较三种索引"
flowchart TD
    A["1,000 组双词<br/>400 中文 · 300 英文 · 300 中英混合"] --> B["相同语料、分词和查询参数"]
    B --> C["默认 BM25"]
    B --> D["QPS<br/>按词项位置关系评分"]
    B --> E["PT15<br/>按 15 个位置区间评分"]
    C --> F["按发布时间排序<br/>比较召回、前十命中、P95、体积"]
    D --> F
    E --> F
```

三种索引共用同一套 schema 和 tokenizer。测试代码的核心是把插件列表传给同一个索引构造函数。

```typescript title="word-pairs.ts · 三组索引配置（简化）"
const plugins =
    name === "qps" ? [pluginQPS()] :
    name === "pt15" ? [pluginPT15()] :
    []; // 空数组使用 Orama 默认 BM25

const database = createSearchIndex(cjk, plugins);
```

| 索引方案 | 双词召回率 | 前十有近邻命中的查询 | 查询 P95 | gzip 索引 |
| --- | ---: | ---: | ---: | ---: |
| Orama 默认 BM25 | 98.88% | 97.8% | 12.73 ms | 5.18 MB |
| QPS | 99.14% | 97.7% | 13.10 ms | 4.79 MB |
| PT15 | 98.88% | 97.8% | 12.19 ms | 3.33 MB |

近邻命中指两个词在同一字段内相距不超过 60 个字符。QPS 的双词召回高 0.26 个百分点，PT15 的索引比 QPS 小 30.6%。我给静态博客选了 **PT15**，接入内容集合后的实际压缩产物为 **3.19 MB**。



现在我在 dev 里就能调分词和结果样式。如果你也想为 Astro 博客做中文搜索，我推荐拿自己的文章试试 Orama，从几个有预期结果的查询开始。 [Stalux 源码](https://github.com/xingwangzhe/stalux) · [Orama 开发文档](https://docs.orama.com/docs/orama-js)


---

**作者：**xingwangzhe

**本文链接：**[https://xingwangzhe.fun/posts/orama-again-replace-pagefind/](https://xingwangzhe.fun/posts/orama-again-replace-pagefind/)

本文采用[知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议](https://creativecommons.org/licenses/by-nc-sa/4.0/)进行许可。