// Поиск: PostgreSQL full-text (конфигурация russian) + pg_trgm. // // Статья попадает в выдачу, если КАЖДОЕ слово запроса нашлось одним из способов: // 1. полнотекстовый поиск по началу слова («узип», «шкос»: с учётом русских окончаний); // 2. подстрока в нормализованном тексте («2273» внутри «2273-245»); // 3. подстрока в «сжатом» тексте без пробелов и дефисов («MG12» → «MG-12», «ral 7024» → «RAL7024»). // Если так ничего не нашлось, включается поиск с опечатками (похожесть триграмм). // // Порядок выдачи: заголовок > «Главное» > теги и оборудование > остальной текст. import { Prisma } from '@prisma/client'; import { compactSearch, normalizeSearch, type Highlight, type SearchResponse } from '@kb/shared'; import { prisma } from './db.js'; import type { StoredFact } from './services/articles.js'; const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const likeEsc = (s: string) => s.replace(/[\\%_]/g, '\\$&'); /** Слова запроса: буквы и цифры, десятичное число целиком. «патч-корд sip 1,2» → [патч, корд, sip, «1,2»]. */ export function tokenize(q: string): string[] { return [...new Set(normalizeSearch(q).match(/\d+(?:,\d+)+|[\p{L}\p{N}]+/gu) ?? [])].slice(0, 8); } /** * Регулярное выражение для подсветки совпадений в исходном тексте (с заглавными буквами, «ё» и дефисами). * Между символами слова допускаем пробел или дефис: так «mg12» подсветит «MG-12». */ export function highlightRegex(q: string): RegExp | null { const tokens = tokenize(q); const whole = compactSearch(q); // Одиночные буквы и цифры не подсвечиваем: «м» из «1,2 м» раскрасила бы весь текст const variants = [...new Set([whole, ...tokens])].filter((v) => v.length >= 2).sort((a, b) => b.length - a.length); if (!variants.length) return null; const pattern = variants .map((t) => [...t] .map((ch) => (ch === 'е' ? '[её]' : ch === ',' ? '[.,]' : esc(ch))) // Разделители допускаем только в «артикулах» (есть цифра), иначе слова склеятся через пробел .join(/\d/.test(t) ? '[\\s\\-–—.]?' : ''), ) .join('|'); return new RegExp(pattern, 'giu'); } export function highlight(text: string, re: RegExp | null): Highlight[] { if (!re || !text) return [{ t: text, hit: false }]; const out: Highlight[] = []; let last = 0; // matchAll продолжает с re.lastIndex: сбрасываем, иначе после exec() часть совпадений потеряется re.lastIndex = 0; for (const m of text.matchAll(re)) { const at = m.index ?? 0; if (!m[0]) continue; if (at > last) out.push({ t: text.slice(last, at), hit: false }); out.push({ t: m[0], hit: true }); last = at + m[0].length; } if (last < text.length) out.push({ t: text.slice(last), hit: false }); return out.length ? out : [{ t: text, hit: false }]; } const hasHit = (h: Highlight[]) => h.some((x) => x.hit); /** Все слова запроса есть в тексте (как подстрока или в сжатом виде)? */ function matchesAll(text: string, tokens: string[], whole: string): boolean { const norm = normalizeSearch(text); const compact = compactSearch(text); if (whole.length >= 3 && compact.includes(whole)) return true; return tokens.every((t) => norm.includes(t) || compact.includes(t)); } /** Кусок текста вокруг первого совпадения, чтобы было понятно, где нашлось. */ function snippet(lines: string[], re: RegExp | null, fallback: string): string { if (re) { for (const line of lines) { re.lastIndex = 0; const m = re.exec(line); if (!m) continue; const start = Math.max(0, m.index - 50); const end = Math.min(line.length, m.index + m[0].length + 90); return (start > 0 ? '…' : '') + line.slice(start, end).trim() + (end < line.length ? '…' : ''); } } return fallback; } interface Row { id: string; slug: string; title: string; summary: string; tags: string[]; equipment: string[]; docCode: string | null; pinned: boolean; sectionId: string; sectionName: string; bodyMd: string; facts: StoredFact[]; rank: number; sim: number; } const stripMd = (s: string) => s.replace(/\*\*/g, ''); export async function search(q: string, visibleOnly: boolean): Promise { const tokens = tokenize(q); const whole = compactSearch(q); if (!tokens.length) return { q, facts: [], articles: [] }; // Условие на каждое слово: подстрока, сжатая подстрока или (для слов от 3 букв) полнотекстовое // совпадение по началу слова с учётом окончаний: «стойки» найдёт «стойка». const perToken = tokens.map((t) => { const like = `%${likeEsc(t)}%`; const fts = /^\p{L}{3,}$/u.test(t) ? Prisma.sql` OR a."searchVector" @@ to_tsquery('russian', ${`${t}:*`})` : Prisma.empty; return Prisma.sql`(a."searchNorm" LIKE ${like} OR a."searchCompact" LIKE ${like}${fts})`; }); const allTokens = Prisma.join(perToken, ' AND '); // Полнотекстовый запрос для ранжирования (веса A–D): «патч:* | корд:* | sip:*» const words = tokens.filter((t) => /^[\p{L}\p{N}]{2,}$/u.test(t)); const tsq = words.length ? words.map((t) => `${t}:*`).join(' | ') : 'zzzzzz'; const qn = normalizeSearch(q); const publicOnly = visibleOnly ? Prisma.sql`AND a.visibility = 'PUBLIC'` : Prisma.empty; const select = Prisma.sql` SELECT a.id, a.slug, a.title, a.summary, a.tags, a.equipment, a."docCode", a.pinned, a."sectionId", s.name AS "sectionName", a."bodyMd", a.facts, ts_rank(a."searchVector", to_tsquery('russian', ${tsq}))::float8 AS rank, word_similarity(${qn}, a."searchNorm")::float8 AS sim FROM "Article" a JOIN "Section" s ON s.id = a."sectionId" WHERE a.status = 'PUBLISHED' ${publicOnly}`; let rows = await prisma.$queryRaw` ${select} AND ( (${allTokens}) OR (${whole.length >= 3} AND a."searchCompact" LIKE ${`%${likeEsc(whole)}%`}) ) LIMIT 60`; // Ничего не нашли: пробуем с опечатками («шкоос», «узпи») let fuzzy = false; if (!rows.length && qn.length >= 3) { fuzzy = true; rows = await prisma.$queryRaw` ${select} AND word_similarity(${qn}, a."searchNorm") > 0.45 ORDER BY sim DESC LIMIT 10`; } const re = fuzzy ? null : highlightRegex(q); const scored = rows.map((r) => { const meta = [...r.tags, ...r.equipment, r.docCode ?? ''].join('\n'); const facts = (r.facts ?? []).map((f) => `${f.label} ${stripMd(f.value)}`).join('\n'); let score = r.rank * 10 + r.sim; if (matchesAll(r.title, tokens, whole)) score += 100; if (matchesAll(`${facts}\n${r.summary}`, tokens, whole)) score += 40; if (matchesAll(meta, tokens, whole)) score += 20; // Шпаргалка содержит всё подряд: чуть опускаем её, чтобы первой шла статья-источник if (r.pinned) score -= 15; return { r, score }; }); scored.sort((a, b) => b.score - a.score || a.r.title.localeCompare(b.r.title, 'ru')); const titles = new Map( (await prisma.article.findMany({ select: { slug: true, title: true } })).map((a) => [a.slug, a.title]), ); const articles = scored.slice(0, 20).map(({ r }) => { // Текст статьи без разметки, построчно: ищем строку с совпадением const lines = [ ...(r.facts ?? []).map((f) => `${f.label ? `${f.label}: ` : ''}${stripMd(f.value)}`), r.equipment.join(', '), r.tags.join(', '), r.docCode ?? '', ...r.bodyMd .split('\n') .map((l) => l .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') .replace(/\[\[[^\]]+\]\]/g, '') .replace(/^[\s>#|:-]+|\*\*|- \[[ x]\] /g, '') .replace(/\s*\|\s*/g, ' · ') .trim(), ), ].filter(Boolean); return { slug: r.slug, title: highlight(r.title, re), section: r.sectionName, sectionId: r.sectionId, snippet: highlight(snippet(hasHit(highlight(r.summary, re)) ? [r.summary] : lines, re, r.summary), re), pinned: r.pinned, }; }); // «Цифры»: пункты «Главного» и строки шпаргалки, в которых встречается запрос const facts: SearchResponse['facts'] = []; const seen = new Set(); if (!fuzzy) { for (const { r } of scored) { for (const f of r.facts ?? []) { const plain = stripMd(f.value); if (!matchesAll(`${f.label} ${plain}`, tokens, whole)) continue; // Крупно показываем то, что в статье выделено жирным: это и есть «цифра» const bolds = [...f.value.matchAll(/\*\*(.+?)\*\*/g)].map((m) => m[1]!); const big = bolds.length ? bolds.join(' · ') : plain; const small = big === plain ? f.label : f.label ? `${f.label}: ${plain}` : plain; const key = normalizeSearch(`${big}|${f.label}`); if (seen.has(key)) continue; seen.add(key); const links = (f.links?.length ? f.links : [r.slug]).map((slug) => ({ slug, title: titles.get(slug) ?? slug })); facts.push({ value: highlight(big, re), label: highlight(small, re), links, sectionId: r.sectionId, cheat: r.pinned }); } } } return { q, facts: facts.slice(0, 12), articles }; }