{
  "id": "add-postgres-full-text-search",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "zh",
  "url": "/zh/playbooks/add-postgres-full-text-search",
  "title": "Prompt-to-PR：添加 PostgreSQL 全文搜索",
  "description": "SOP 用于添加原生 PostgreSQL 全文搜索，使用 tsvector、GIN 索引、ts_rank 和 Next.js 搜索 API — 无需第三方搜索服务。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "postgres",
    "nextjs",
    "typescript",
    "search",
    "sql"
  ],
  "difficulty": "hard",
  "updated": "2026-06-08",
  "markdown": "PostgreSQL 内置的全文搜索可以满足大多数产品搜索需求，无需 Elasticsearch 或 Algolia。本操作指南将添加一个 `tsvector` 列、一个 GIN 索引，以及一个位于 Next.js API 路由后方的排序搜索查询。\n\n## 1. 需求\n\n在 `posts` 表（列：`title`、`body`、`tags`）上添加全文搜索。搜索结果应按相关性排序并显示片段高亮。实现必须使用生成的 `tsvector` 列（而非查询时计算），以便使用 GIN 索引。\n\n## 2. 首个提示\n\n```txt title=\"First Prompt\"\nAdd native PostgreSQL full-text search to the posts table in this project.\n\nDatabase: PostgreSQL. ORM/query builder: [Drizzle / postgres.js — use whichever\nis already in src/db/].\n\nStep 1 — migration:\n  Create a migration file (or Drizzle schema change) that:\n  a. Adds a generated column:\n       search_vector tsvector GENERATED ALWAYS AS (\n         setweight(to_tsvector('english', coalesce(title, '')), 'A') ||\n         setweight(to_tsvector('english', coalesce(body, '')), 'B') ||\n         setweight(to_tsvector('english', coalesce(tags, '')), 'C')\n       ) STORED;\n  b. Creates a GIN index on search_vector:\n       CREATE INDEX posts_search_idx ON posts USING gin(search_vector);\n\nStep 2 — query function:\n  Create `src/lib/queries/search.ts` exporting `searchPosts(q: string, limit = 10)`.\n  The query must:\n  - Convert the user query to a tsquery: `websearch_to_tsquery('english', $1)`.\n  - Filter: `search_vector @@ query`.\n  - Rank: `ts_rank(search_vector, query) DESC`.\n  - Return: id, title, ts_headline('english', body, query,\n      'MaxWords=30, MinWords=15, ShortWord=3, HighlightAll=false') AS snippet.\n  - Use parameterized query (no string interpolation of the user input).\n\nStep 3 — API route:\n  Create `src/app/api/search/route.ts` (GET). Read `q` from URL search params.\n  Return 400 if q is empty or shorter than 2 chars. Return JSON array of results.\n  Add cache-control: public, max-age=60.\n\nStep 4 — do not touch any UI components.\n```\n\n## 3. 预期文件更改\n\n```txt\nsrc/db/migrations/<timestamp>_add_search_vector.sql   (new — or Drizzle migration)\nsrc/db/schema.ts                                       (search_vector column if Drizzle)\nsrc/lib/queries/search.ts                              (new — searchPosts function)\nsrc/app/api/search/route.ts                            (new — GET endpoint)\n```\n\n## 4. 审查清单\n\n- `GENERATED ALWAYS AS ... STORED` — 列是存储的（而非虚拟的），因此可以使用 GIN 索引。确认存在 `STORED` 关键字。\n- 使用 `websearch_to_tsquery`（而非 `to_tsquery`）— 处理来自不可信输入的多词和短语查询，不会出现语法错误。\n- 用户提供的查询作为 SQL 参数传递，绝不进行字符串插值。\n- `ts_rank` 对结果排序 — 而非按字母顺序或插入顺序。\n- `ts_headline` 长度受限（MaxWords=30），避免返回过大的片段。\n- GIN 索引名称明确 — 便于在需要时删除/重建。\n- API 路由验证最小查询长度（2个字符），避免类似 `'a':*` 的全表扫描 tsquery。\n- 在响应中设置 `Cache-Control: public, max-age=60` — 搜索结果可进行短时间缓存。\n\n## 5. 测试命令\n\n```bash\n# Run the migration\nnpx drizzle-kit migrate\n# or: psql $DATABASE_URL < migration.sql\n\n# Verify the generated column and index exist\npsql $DATABASE_URL -c \"\\d posts\" | grep search_vector\npsql $DATABASE_URL -c \"\\di posts_search_idx\"\n\n# Query performance — confirm index scan, not seq scan\npsql $DATABASE_URL -c \"\n  EXPLAIN ANALYZE\n  SELECT id FROM posts\n  WHERE search_vector @@ websearch_to_tsquery('english', 'your test query')\n  LIMIT 10;\n\" | grep \"Index Scan\"\n\n# Test the API endpoint\nbun dev &\ncurl \"http://localhost:3000/api/search?q=your+test+query\" | jq .\n\n# Confirm empty query returns 400\ncurl -o /dev/null -w \"%{http_code}\" \"http://localhost:3000/api/search?q=\"\n# Expect: 400\n```\n\n## 6. 常见失败原因\n\n- **顺序扫描而非索引扫描** — `VIRTUAL` 列（而非 `STORED`）。在 PostgreSQL 中，只有 `STORED` 生成的列可以被索引。确认迁移使用 `STORED`。\n- **`to_tsquery` 对多词输入抛出异常** — `to_tsquery('english', 'quick brown')` 是语法错误。对于用户提供的字符串，始终使用 `websearch_to_tsquery`。\n- **`ts_headline` 返回整个正文** — 意外设置了 `HighlightAll=true`，或未设置 `MaxWords`。检查选项字符串。\n- **GIN 索引未用于 `LIKE` 查询** — 确保 WHERE 子句使用 `@@` 运算符，而非 `LIKE` 或 `ILIKE`。全文搜索和 `LIKE` 是分开的。\n- **迁移在现有数据上失败** — `GENERATED` 列在创建时填充；对于大表，这可能很慢。在事务中运行并检查进度。\n\n## 7. 修复提示\n\n```txt title=\"Fix Prompt\"\nEXPLAIN ANALYZE shows a sequential scan instead of an index scan on the\nposts table. The search_vector column was added as VIRTUAL (or without\nthe STORED keyword) so PostgreSQL cannot create a GIN index on it.\n\nFix the migration:\n  ALTER TABLE posts DROP COLUMN search_vector;\n  ALTER TABLE posts ADD COLUMN search_vector tsvector\n    GENERATED ALWAYS AS (\n      setweight(to_tsvector('english', coalesce(title, '')), 'A') ||\n      setweight(to_tsvector('english', coalesce(body, '')), 'B')\n    ) STORED;\n  CREATE INDEX posts_search_idx ON posts USING gin(search_vector);\n\nConfirm the word STORED appears in the column definition.\n```\n\n## 8. PR 描述\n\n```md title=\"PR description\"\n## Feature: PostgreSQL native full-text search on posts\n\n- Generated `tsvector` column (`STORED`) with weighted fields:\n  title (A), body (B), tags (C)\n- GIN index `posts_search_idx` — index scans confirmed via `EXPLAIN ANALYZE`\n- `searchPosts(q, limit)` uses `websearch_to_tsquery` (safe for user input)\n  and `ts_rank` for relevance ordering\n- `ts_headline` snippets (max 30 words) with matched terms highlighted\n- GET `/api/search?q=` — validates query length, returns ranked JSON,\n  `Cache-Control: public, max-age=60`\n\nNo third-party search dependency added.\n```"
}