perf: 错题列表补充筛选联合索引并建立千级基准

- ErrorItem 增加 (userId,subjectId/paperLevel/questionType,createdAt) 联合索引
- KnowledgeTag 增加 name 索引
- 迁移测试校验新索引
- 新增 bench-error-list.mjs 与性能文档,1k/5k p75 与 EXPLAIN 可复现
Refs: https://github.com/margrop/wrong-notebook/issues/64
This commit is contained in:
margrop
2026-12-02 18:18:21 +08:00
parent db5478a4e0
commit 4c557c36fd
5 changed files with 263 additions and 1 deletions

View File

@@ -0,0 +1,42 @@
# 错题列表千级数据性能
对应 issue #64:在 1000~5000 道错题规模下,保持列表、计数与常用筛选的稳定延迟。
## 索引
`ErrorItem` 在原有 `(userId, createdAt)` 与 `subjectId` 之外,增加三个筛选 + 排序的联合索引:
- `(userId, subjectId, createdAt)`:错题本筛选;
- `(userId, paperLevel, createdAt)`:卷别筛选;
- `(userId, questionType, createdAt)`:题型筛选。
`KnowledgeTag` 增加 `name` 索引,按知识点名筛选错题时不必全表扫描标签。
年级学期仍用 `contains` 匹配别名(如「初一」「7年级」),LIKE 无法走索引;知识点筛选经标签关联表,已有关系索引。
## 基准方法
```bash
node scripts/bench-error-list.mjs --rounds 20 --counts 1000,5000
```
脚本在系统临时目录按当前 schema 建库,写入 1k/5k 合成错题,执行与 `/api/error-items/list` 相同的「count + 分页查询」,输出 p50/p75/p95 与 `EXPLAIN QUERY PLAN`。临时库结束后删除。
## 结果(本机 2026-12-02,20 轮,单位 ms)
| 场景 | 1k p75 | 5k p75 |
|---|---:|---:|
| 默认列表(第 1 页) | 0.32 | 0.39 |
| 按错题本 | 0.28 | 0.38 |
| 按卷别 | 0.25 | 0.28 |
| 按单题型 | 0.24 | 0.27 |
| 按多题型 | 0.28 | 0.32 |
| 关键字搜索(LIKE 四个字段) | 0.75 | 1.92 |
默认列表与筛选的 p75 在 5 倍数据下只增长约 0.1~0.15 ms,不随题量线性恶化;搜索仍随题量近似线性增长。
`EXPLAIN QUERY PLAN` 确认默认、错题本、卷别、单题型分别命中对应索引;多题型 `IN` 由规划器选择 `(userId, createdAt)`,仍在索引内完成过滤与排序。
## 搜索方案评估
当前关键字搜索用 SQLite `LIKE '%词%'`,无法利用普通索引;5k 题约 1.9 ms(p75),在现有规模可接受。若题量达到万级且搜索成为主要操作,再引入 FTS5 虚表与触发器同步题干、解析、作答、错因,并把标签名搜索并入;现阶段不引入 FTS,避免额外的迁移与双写维护。

View File

@@ -0,0 +1,11 @@
-- CreateIndex
CREATE INDEX "ErrorItem_userId_subjectId_createdAt_idx" ON "ErrorItem"("userId", "subjectId", "createdAt");
-- CreateIndex
CREATE INDEX "ErrorItem_userId_paperLevel_createdAt_idx" ON "ErrorItem"("userId", "paperLevel", "createdAt");
-- CreateIndex
CREATE INDEX "ErrorItem_userId_questionType_createdAt_idx" ON "ErrorItem"("userId", "questionType", "createdAt");
-- CreateIndex
CREATE INDEX "KnowledgeTag_name_idx" ON "KnowledgeTag"("name");

View File

@@ -132,6 +132,8 @@ model KnowledgeTag {
@@index([parentId])
@@index([subject])
@@index([tagSet])
// 按标签名精确/包含筛选错题时不必回表扫全表
@@index([name])
}
model Subject {
@@ -237,6 +239,10 @@ model ErrorItem {
// 列表、统计都按用户取错题并按时间排序;SQLite 不会自动给外键建索引
@@index([userId, createdAt])
@@index([subjectId])
// 常用筛选 + 按时间排序:覆盖 (userId, 筛选列, createdAt) 的查询,避免取到候选后临时排序
@@index([userId, subjectId, createdAt])
@@index([userId, paperLevel, createdAt])
@@index([userId, questionType, createdAt])
@@unique([userId, seqNo])
}

View File

@@ -0,0 +1,194 @@
/**
* 错题列表千级数据基准:在临时 SQLite 库中按真实 schema 建库,写入 1k/5k 合成错题,
* 测量列表接口的「count + 分页查询」耗时,并输出 EXPLAIN QUERY PLAN 证明筛选走索引。
*
* 用法:node scripts/bench-error-list.mjs [--rounds 25] [--counts 1000,5000]
* 临时库在系统临时目录,结束后删除,不写入仓库。
*/
import { execFileSync } from 'node:child_process';
import { cpSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { PrismaClient } from '@prisma/client';
const PRISMA_CLI = resolve('node_modules/prisma/build/index.js');
const SCHEMA = resolve('prisma/schema.prisma');
const PAGE_SIZE = 20;
const CHUNK = 500;
const QUESTION_TYPES = ['single_choice', 'fill_blank', 'solution', 'reading'];
function parseArgs() {
const args = process.argv.slice(2);
const rounds = Number(args[args.indexOf('--rounds') + 1] || 25);
const counts = (args[args.indexOf('--counts') + 1] || '1000,5000').split(',').map(Number);
return { rounds: Number.isFinite(rounds) && rounds > 0 ? rounds : 25, counts };
}
/** 用 prisma db push 按当前 schema 建临时库,保证索引与迁移后的生产库一致 */
function createDatabase(directory) {
const databasePath = join(directory, 'bench.db');
const schemaPath = join(directory, 'schema.prisma');
cpSync(SCHEMA, schemaPath);
execFileSync(process.execPath, [PRISMA_CLI, 'db', 'push', '--schema', schemaPath, '--skip-generate'], {
env: { ...process.env, DATABASE_URL: 'file:' + databasePath },
encoding: 'utf8',
stdio: 'pipe',
timeout: 120_000,
});
return databasePath;
}
function percentile(values, ratio) {
const sorted = [...values].sort((left, right) => left - right);
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1));
return sorted[index];
}
async function seed(prisma, total) {
const existing = await prisma.errorItem.count();
if (existing >= total) return;
const data = [];
const base = Date.parse('2026-01-01T00:00:00Z');
for (let index = existing; index < total; index++) {
data.push({
id: `bench-item-${index}`,
userId: 'bench-user',
subjectId: 'bench-subject',
paperLevel: `bench-paper-${index % 3}`,
originalImageUrl: 'bench-image',
questionText: `基准题目 ${index}`,
questionType: QUESTION_TYPES[index % QUESTION_TYPES.length],
gradeSemester: index % 2 === 0 ? '七年级上' : '八年级下',
createdAt: new Date(base + index * 60_000),
});
}
for (let start = 0; start < data.length; start += CHUNK) {
await prisma.errorItem.createMany({ data: data.slice(start, start + CHUNK) });
}
}
const SCENARIOS = {
default: (userId) => ({ where: { userId } }),
subject: (userId) => ({ where: { userId, subjectId: 'bench-subject' } }),
paperLevel: (userId) => ({ where: { userId, paperLevel: 'bench-paper-1' } }),
questionType: (userId) => ({ where: { userId, questionType: 'single_choice' } }),
questionTypes: (userId) => ({ where: { userId, questionType: { in: ['single_choice', 'fill_blank'] } } }),
search: (userId) => ({
where: {
userId,
OR: [
{ questionText: { contains: '基准题目 4999' } },
{ analysis: { contains: '基准题目 4999' } },
{ wrongAnswerText: { contains: '基准题目 4999' } },
{ mistakeAnalysis: { contains: '基准题目 4999' } },
],
},
}),
deepPage: (userId) => ({ where: { userId }, skip: 4000 }),
};
async function measure(prisma, name, rounds) {
const scenario = SCENARIOS[name];
const timings = [];
for (let round = 0; round < rounds; round++) {
const args = scenario('bench-user');
const startedAt = process.hrtime.bigint();
await prisma.errorItem.count({ where: args.where });
await prisma.errorItem.findMany({
...args,
orderBy: { createdAt: 'desc' },
skip: args.skip ?? 0,
take: PAGE_SIZE,
select: { id: true, questionText: true, masteryProbability: true },
});
timings.push(Number(process.hrtime.bigint() - startedAt) / 1e6);
}
return {
p50: percentile(timings, 0.5),
p75: percentile(timings, 0.75),
p95: percentile(timings, 0.95),
};
}
/** 与列表接口等价的 SQL;EXPLAIN 只用于证明索引覆盖,不计入耗时 */
const EXPLAIN_SQL = {
default: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', PAGE_SIZE, 0],
},
subject: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "subjectId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', 'bench-subject', PAGE_SIZE, 0],
},
paperLevel: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "paperLevel" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', 'bench-paper-1', PAGE_SIZE, 0],
},
questionType: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "questionType" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', 'single_choice', PAGE_SIZE, 0],
},
questionTypes: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND "questionType" IN (?,?) ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', 'single_choice', 'fill_blank', PAGE_SIZE, 0],
},
search: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? AND ("questionText" LIKE ? OR "analysis" LIKE ? OR "wrongAnswerText" LIKE ? OR "mistakeAnalysis" LIKE ?) ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', '%基准题目 4999%', '%基准题目 4999%', '%基准题目 4999%', '%基准题目 4999%', PAGE_SIZE, 0],
},
deepPage: {
sql: 'SELECT "id" FROM "ErrorItem" WHERE "userId" = ? ORDER BY "createdAt" DESC LIMIT ? OFFSET ?',
params: ['bench-user', PAGE_SIZE, 4000],
},
};
async function explain(prisma, name) {
const { sql, params } = EXPLAIN_SQL[name];
const plan = await prisma.$queryRawUnsafe('EXPLAIN QUERY PLAN ' + sql, ...params);
return plan.map((row) => row.detail);
}
async function main() {
const { rounds, counts } = parseArgs();
const directory = mkdtempSync(join(tmpdir(), 'wrong-notebook-bench-'));
const databasePath = createDatabase(directory);
const prisma = new PrismaClient({ datasources: { db: { url: 'file:' + databasePath } } });
try {
await prisma.user.create({ data: { id: 'bench-user', email: 'bench@example.com', password: 'bench-only' } });
await prisma.subject.create({ data: { id: 'bench-subject', name: '基准数学', userId: 'bench-user', subjectKey: 'math' } });
for (let index = 0; index < 3; index++) {
await prisma.paperGroup.create({
data: { id: `bench-paper-${index}`, userId: 'bench-user', key: ['a', 'b', 'other'][index], name: `基准卷 ${index}` },
});
}
const results = [];
let seeded = 0;
for (const total of counts) {
await seed(prisma, total);
seeded = total;
const row = { count: total, scenarios: {} };
for (const name of Object.keys(SCENARIOS)) {
if (name === 'deepPage' && total < 4000) continue;
row.scenarios[name] = await measure(prisma, name, rounds);
}
results.push(row);
}
console.log(JSON.stringify({ rounds, seeded, results }, null, 2));
console.log('\nEXPLAIN QUERY PLAN(5k 数据)');
for (const name of Object.keys(SCENARIOS)) {
if (name === 'deepPage' && seeded < 4000) continue;
console.log(`\n${name}:`);
for (const line of await explain(prisma, name)) console.log(' ' + line);
}
} finally {
await prisma.$disconnect();
rmSync(directory, { recursive: true, force: true });
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});

View File

@@ -78,7 +78,16 @@ function expectConstraints() {
expect(database!.prepare('PRAGMA foreign_key_list("ErrorItem")').all())
.toContainEqual(expect.objectContaining({ table: 'PaperGroup', from: 'paperLevel', on_delete: 'SET NULL' }));
expect(database!.prepare('PRAGMA index_list("ErrorItem")').all().map((index) => index.name))
.toEqual(expect.arrayContaining(['ErrorItem_shortId_key', 'ErrorItem_userId_createdAt_idx', 'ErrorItem_subjectId_idx']));
.toEqual(expect.arrayContaining([
'ErrorItem_shortId_key',
'ErrorItem_userId_createdAt_idx',
'ErrorItem_subjectId_idx',
'ErrorItem_userId_subjectId_createdAt_idx',
'ErrorItem_userId_paperLevel_createdAt_idx',
'ErrorItem_userId_questionType_createdAt_idx',
]));
expect(database!.prepare('PRAGMA index_list("KnowledgeTag")').all().map((index) => index.name))
.toContain('KnowledgeTag_name_idx');
expect(database!.prepare('PRAGMA index_list("PaperGroup")').all().map((index) => index.name))
.toEqual(expect.arrayContaining(['PaperGroup_userId_key_key', 'PaperGroup_userId_name_key', 'PaperGroup_userId_order_idx']));
}