revert(search): 병행 검색 재정렬 되돌림 — Ollama 결과 앞·SearXNG 뒤 이어 붙이기로 복귀

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-09-30 01:15:19 +09:00
1 parent 1ab06b8cdc
commit 107909812b
3 files changed
+16 -165

No files matched your search

+14 -95
View File
@@ -35,115 +35,34 @@ export interface MergeOptions {
primaryCharCap: number;
/** 뒤쪽 결과당 본문 상한 글자수. */
secondaryCharCap: number;
/** 질의 내용어(relevanceTokens). 있으면 제목+본문 앞부분의 포함률을 순위에 반영한다. */
queryTokens?: string[];
/** 앞쪽(Ollama) 가중치. 실측에서 평균적으로 더 정확해 약간의 우선권을 준다. */
primaryWeight?: number;
/** "오늘/최신/현재" 같은 시점 질의인가. 참이면 최근 날짜가 적힌 결과에 가산점을 준다. */
freshness?: boolean;
/** 현재 시각(ms). 테스트에서 고정하려고 주입한다. 기본은 Date.now(). */
now?: number;
}
/** RRF(reciprocal rank fusion) 상수. 60이 표준값이다 — 상위 순위 간 격차를 완만하게 만든다. */
const RRF_K = 60;
/** 포함률 1.0(질의어를 전부 담음)이 순위 점수에 더하는 크기. RRF 한 목록 1위(≈0.0164)와 비슷한 규모다. */
const COVERAGE_WEIGHT = 0.02;
/** 포함률을 셀 때 보는 본문 앞부분 길이. Ollama는 본문이 수천 자라 전체를 보면 길이만으로 유리해진다. */
const COVERAGE_TEXT_CHARS = 600;
/** 최근성 가산점 크기 — 포함률 보너스와 같은 규모다. */
const RECENCY_WEIGHT = 0.02;
/** 날짜를 찾을 때 보는 앞부분 길이. 기사 본문은 "발행일: 2026-09-25"처럼 앞에 날짜가 온다. */
const DATE_TEXT_CHARS = 1500;
/** 텍스트 앞부분에서 (미래가 아닌) 가장 최근 날짜를 ms로 돌려준다. 없으면 null. */
export function latestDateMs(text: string, now: number): number | null {
const t = String(text || '').slice(0, DATE_TEXT_CHARS);
const MONTHS: Record<string, number> = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
const found: number[] = [];
const push = (y: number, m: number, d: number) => {
if (y < 2000 || y > 2100 || m < 1 || m > 12 || d < 1 || d > 31) return;
const ms = Date.UTC(y, m - 1, d);
if (ms <= now + 86_400_000) found.push(ms);
};
for (const m of t.matchAll(/(20\d\d)[-./](\d{1,2})[-./](\d{1,2})/g)) push(+m[1], +m[2], +m[3]);
for (const m of t.matchAll(/(20\d\d)\s*년\s*(\d{1,2})\s*월\s*(\d{1,2})\s*일/g)) push(+m[1], +m[2], +m[3]);
for (const m of t.matchAll(/\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+(\d{1,2}),?\s+(20\d\d)/gi)) push(+m[3], MONTHS[m[1].toLowerCase()], +m[2]);
return found.length ? Math.max(...found) : null;
}
function recencyOf(item: MergeItem, now: number): number {
const ms = latestDateMs(`${item.title} ${item.snippet || ''}`, now);
if (ms === null) return 0;
const days = (now - ms) / 86_400_000;
if (days <= 7) return 1;
if (days <= 30) return 0.6;
if (days <= 90) return 0.2;
return 0;
}
function coverageOf(item: MergeItem, tokens: string[] | undefined): number {
if (!tokens || tokens.length === 0) return 0;
const text = `${item.title} ${(item.snippet || '').slice(0, COVERAGE_TEXT_CHARS)}`.toLowerCase();
let hit = 0;
for (const t of tokens) if (text.includes(t.toLowerCase())) hit++;
return hit / tokens.length;
}
/**
* 두 목록을 합쳐 재정렬한다.
*
* 순위 = RRF(각 엔진 안에서의 순위) + 질의어 포함률 보너스 (+ 시점 질의면 최근성 보너스).
* - 두 엔진이 모두 올린 URL은 RRF 점수가 합쳐져 위로 간다(독립된 두 검색이 동의한 결과).
* - 한쪽에만 있어도 그 엔진 안에서 순위가 높고 질의어를 잘 담았으면 올라온다 — SearXNG가 더 좋은
* 질의(코스피 종가, OpenWrt 릴리즈)에서 Ollama 3건 뒤에 묻히던 문제를 푼다.
* 겹치는 URL은 한 번만 나오고, 본문이 더 긴 쪽을 쓴다(정보 손실 방지).
* primary를 앞에 그대로 두고, secondary는 primary와 URL이 겹치지 않는 것만 이어 붙인다.
* 겹치는 URL이 secondary 쪽 본문이 더 길면 그 본문을 primary 항목에 채워 넣는다(정보 손실 방지).
*/
export function mergeSearchResults(primary: MergeItem[], secondary: MergeItem[], opts: MergeOptions): MergeItem[] {
const cap = (s: string, n: number) => (s.length > n ? s.slice(0, n) : s);
const wP = opts.primaryWeight ?? 1.15;
type Entry = { item: MergeItem; rrf: number; order: number };
const entries: Entry[] = [];
const index = new Map<string, Entry>();
primary.forEach((r, i) => {
const key = normalizeUrlKey(r.url);
if (index.has(key)) return;
const e: Entry = { item: { ...r, snippet: cap(r.snippet || '', opts.primaryCharCap) }, rrf: wP / (RRF_K + i + 1), order: entries.length };
entries.push(e);
index.set(key, e);
});
const out: MergeItem[] = primary.map((r) => ({ ...r, snippet: cap(r.snippet || '', opts.primaryCharCap) }));
const index = new Map<string, MergeItem>();
for (const r of out) index.set(normalizeUrlKey(r.url), r);
let added = 0;
secondary.forEach((r, i) => {
for (const r of secondary) {
const key = normalizeUrlKey(r.url);
const existing = index.get(key);
const rrf = 1 / (RRF_K + i + 1);
if (existing) {
existing.rrf += rrf;
const alt = cap(r.snippet || '', opts.primaryCharCap);
if (alt.length > existing.item.snippet.length) existing.item.snippet = alt;
return;
if (alt.length > existing.snippet.length) existing.snippet = alt;
continue;
}
if (added >= opts.maxSecondary) return;
const e: Entry = { item: { ...r, snippet: cap(r.snippet || '', opts.secondaryCharCap) }, rrf, order: entries.length };
entries.push(e);
index.set(key, e);
if (added >= opts.maxSecondary) continue;
const item = { ...r, snippet: cap(r.snippet || '', opts.secondaryCharCap) };
out.push(item);
index.set(key, item);
added++;
});
const now = opts.now ?? Date.now();
return entries
.map((e) => ({
e,
score: e.rrf
+ COVERAGE_WEIGHT * coverageOf(e.item, opts.queryTokens)
+ (opts.freshness ? RECENCY_WEIGHT * recencyOf(e.item, now) : 0),
}))
.sort((a, b) => b.score - a.score || a.e.order - b.e.order)
.map((x) => x.e.item);
}
return out;
}
/** 본문을 자르지 않는 stdout 렌더링(SearXNG 쪽은 호출자가 짧게 잘라 넘긴다). */
+2 -9
View File
@@ -501,16 +501,11 @@ export function relevanceTokens(query: string): string[] {
return parts.filter(t => (CJK.test(t) ? t.length >= 2 : t.length >= 4));
}
/** "오늘/최신/현재" 같은 시점 표현이 있는 질의인가. rankResults와 병행 검색 재정렬이 같은 기준을 쓴다. */
function isFreshnessQuery(query: string): boolean {
const q = query.toLowerCase();
return /\b(current|latest|today|now|as of|recent)\b/.test(q) || /(지금|현재|오늘|최신|요즘|방금)/.test(q);
}
function rankResults(query: string, results: SearchResultItem[]) {
const q = query.toLowerCase();
// 시점 표현도 영어만 있었다 — 같은 뜻의 한국어 질문은 이 배수를 받은 적이 없다.
const freshness = isFreshnessQuery(query);
const freshness = /\b(current|latest|today|now|as of|recent)\b/.test(q)
|| /(지금|현재|오늘|최신|요즘|방금)/.test(q);
const tokens = relevanceTokens(q);
return [...results]
.map(r => {
@@ -1097,8 +1092,6 @@ async function runSearchProviders(args: { query: string; max_results?: number })
maxSecondary: Math.min(Math.max(limit, 5), 10),
primaryCharCap: DUAL_OLLAMA_SNIPPET_CAP,
secondaryCharCap: 400,
queryTokens: relevanceTokens(args.query),
freshness: isFreshnessQuery(args.query),
});
if (merged.length > 0) {
const answer = (ol?.data as any)?.answer || (sx?.data as any)?.answer;
-61
View File
@@ -81,64 +81,3 @@ describe('normalizePreferredProvider', () => {
assert.equal(normalizePreferredProvider('searxng'), 'searxng');
});
});
describe('mergeSearchResults 재정렬(RRF + 질의어 포함률)', () => {
test('두 엔진이 모두 올린 URL은 Ollama 1위보다 위로 간다', () => {
const m = mergeSearchResults(
[it('https://o.com/1'), it('https://o.com/2'), it('https://shared.com/x')],
[it('https://shared.com/x'), it('https://s.com/2')],
OPTS,
);
assert.equal(m[0].url, 'https://shared.com/x');
});
test('질의어를 잘 담은 SearXNG 결과가, 무관한 Ollama 결과보다 위로 간다', () => {
const m = mergeSearchResults(
[it('https://o.com/off', '전혀 다른 이야기', '무관한 제목')],
[it('https://s.com/on', '코스피 종가 마감 시황', '코스피 오늘 종가')],
{ ...OPTS, queryTokens: ['코스피', '종가'] },
);
assert.equal(m[0].url, 'https://s.com/on');
});
test('포함률 정보가 없으면 Ollama 우선순위가 유지된다', () => {
const m = mergeSearchResults([it('https://o.com/1')], [it('https://s.com/1')], OPTS);
assert.equal(m[0].url, 'https://o.com/1');
});
test('Ollama 본문이 길어도 포함률은 앞부분만 본다 — 길이만으로 유리해지지 않는다', () => {
const long = 'x'.repeat(2000) + ' 코스피 종가';
const m = mergeSearchResults(
[it('https://o.com/long', long, '제목')],
[it('https://s.com/short', '코스피 종가', '코스피 종가')],
{ ...OPTS, queryTokens: ['코스피', '종가'] },
);
assert.equal(m[0].url, 'https://s.com/short');
});
});
import { latestDateMs } from '../src/tools/search-merge';
describe('최근성 가산점(시점 질의 전용)', () => {
const NOW = Date.UTC(2026, 8, 30); // 2026-09-30
const day = (y: number, m: number, d: number) => Date.UTC(y, m - 1, d);
test('여러 표기의 날짜를 읽고, 가장 최근 것을 돌려준다', () => {
assert.equal(latestDateMs('발행일: 2026-09-25 16:05', NOW), day(2026, 9, 25));
assert.equal(latestDateMs('2026년 9월 28일 종가', NOW), day(2026, 9, 28));
assert.equal(latestDateMs('Sep 11, 2026 and Sep 28, 2026', NOW), day(2026, 9, 28));
assert.equal(latestDateMs('날짜 없음', NOW), null);
});
test('미래 날짜는 무시한다(전망·예정 기사)', () => {
assert.equal(latestDateMs('2026-12-31 예정', NOW), null);
});
test('시점 질의에서는 최근 날짜 결과가, 아닌 질의에서는 순서가 그대로다', () => {
const oldOne = it('https://o.com/old', '2025-01-10 기사 본문', 'a');
const fresh = it('https://s.com/new', '2026-09-29 기사 본문', 'b');
const fr = mergeSearchResults([oldOne], [fresh], { ...OPTS, freshness: true, now: NOW });
assert.equal(fr[0].url, 'https://s.com/new');
const nf = mergeSearchResults([oldOne], [fresh], { ...OPTS, freshness: false, now: NOW });
assert.equal(nf[0].url, 'https://o.com/old');
});
});