/api/web/records 是 findAndCountAll,列表本身走 idx_scan_time 只要 0.5ms, 慢的是后面那条 count(id):MySQL 只能选 (subject_id, barcode),索引里没有 scanner_id,于是按主键逐行回表判断 —— 线上 16.5 万条时 Rows_examined ≈ 33 万, 慢查询日志里 3.2s~9.9s(冷缓存时走磁盘)。 补 (subject_id, scanner_id, scan_time) 后 count 变成纯索引扫描(Using index), 实测 0.45s(热)/9.9s(冷) → 0.09s。 - 新增迁移 20261116200000-add-scan-record-list-index.js(幂等,已在生产执行) - sql/schema.sql 基线同步该索引 - README 补索引用途与实测数字 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
47 lines
1.8 KiB
JavaScript
47 lines
1.8 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 扫码记录列表(`/api/web/records`):补一个能被「覆盖」的索引
|
||
*
|
||
* 该接口是 `findAndCountAll`,一次请求会跑两条 SQL:
|
||
* 1. 列表:`WHERE subject_id = ? AND scanner_id IN (...) ORDER BY scan_time DESC, id DESC LIMIT 20`
|
||
* 2. 总数:`WHERE` 同上,但**没有 LIMIT**(`count(id)` 要数完整个集合)
|
||
*
|
||
* 2026-11-16 线上实测(主体 1,约 16.5 万条):
|
||
* - 列表:走 `idx_scan_time` 反向扫 + 过滤,约 28 ms,本来不慢;
|
||
* - 总数:走 `idx_scan_subject_barcode`(`subject_id, barcode`)——索引里没有 `scanner_id`,
|
||
* 只能**逐行回表**判断,`Rows_examined` ≈ 33 万;冷缓存 9.9 s、热缓存 0.45 s。
|
||
* 「第一次打开扫码记录很慢」就是它。
|
||
*
|
||
* 加 `(subject_id, scanner_id, scan_time)` 后,总数变成纯索引扫描(不回表),
|
||
* 顺带让「按设备过滤 + 按时间倒序」的列表也能直接吃索引顺序。
|
||
*
|
||
* 注意:`sql/schema.sql` 基线已同步这个索引,空库执行时幂等。
|
||
*/
|
||
|
||
const INDEX_NAME = 'idx_scan_subject_scanner_time';
|
||
|
||
/** 判断索引是否存在(重跑/已经手工加过的库不报错) */
|
||
async function hasIndex(queryInterface, table, name) {
|
||
try {
|
||
const indexes = await queryInterface.showIndex(table);
|
||
return indexes.some(item => item.name === name);
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
async up(queryInterface) {
|
||
if (await hasIndex(queryInterface, 'scan_records', INDEX_NAME)) return;
|
||
await queryInterface.addIndex('scan_records', [ 'subject_id', 'scanner_id', 'scan_time' ], {
|
||
name: INDEX_NAME,
|
||
});
|
||
},
|
||
|
||
async down(queryInterface) {
|
||
if (!(await hasIndex(queryInterface, 'scan_records', INDEX_NAME))) return;
|
||
await queryInterface.removeIndex('scan_records', INDEX_NAME);
|
||
},
|
||
};
|