Files
o2o-site-AEO/ontology/src/keywords/dedup.service.ts
T
HyeongBaeYangandClaude Opus 5.5 847943a8bc [feat] ontology: 새 숙소 키워드를 OpenAI 로 쌓고 매칭에 쓴다 — 호텔 업종 · 숙소 검색 정정
사전이 고정 데이터셋뿐이라 사전에 없는 숙소는 새 단어를 받지 못했고, 생성분은 MATCH_SOURCES 가
llm 을 빼서 만들어도 추천에 안 나왔다. 숙소 검색은 가까운 키워드를 사전 전체(7천)에서 뽑아
상위가 아무 숙소에도 안 붙은 단어로 차서 `선유도 독채` 가 0건이었다.

- merchants.controller: 처음 보는 업체·기한 지난 업체만 생성, sync 는 처음 보는 업체만 기다림 —
  재빌드마다 불리는 창구라 조건이 없으면 저장마다 요금. 동기 생성 실패는 200 + generation.failed
- generation·dedup·keyword.repository: mock 생성분은 source='mock' — compose 기본이 mock 이라
  키 없는 환경의 가짜 단어가 매칭 후보가 되지 않게
- match.service: llm 출처를 후보에 넣음(brand 는 그 업체 것만), 업종은 뿌리(stay)로 좁힘 —
  새 호텔은 호텔 사전이 비어 잎으로 좁히면 후보 0건
- openai.provider: 미확인 시설·다른 숙박 유형어·가격 주장 금지
- drizzle/0002 · seed: stay.hotel — 시드만 두면 떠 있는 DB 에서 외래키 위반 500
- serving.service: 숙소에 연결된 키워드만 비교, 검색어가 지역을 말하면 그 지역 숙소만 —
  e5-small 은 지역이 틀려도 0.85(`여수 호텔` → 군산 호텔 0.848)라 임계값으로는 못 가른다

tsc 통과. 로컬 :3101 + 실 OpenAI(가짜 숙소 2곳): 첫 발행 7초 · 키워드 12 생성 · 재발행 fresh,
검색 7건(`은파호수공원 근처 호텔`·`선유도 독채`·`군산시내호텔` 적중, `여수 호텔` 0건) 확인 후 테스트 데이터 삭제

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 13:49:37 +09:00

108 lines
3.3 KiB
TypeScript

import { Injectable, Logger } from '@nestjs/common';
import { env } from '../config/env';
import { KeywordIntent } from '../llm/types';
import { KeywordRepository } from './keyword.repository';
import { canonicalizeKeyword, isBanned, normalizeKeyword } from './normalize';
export type DedupAction =
| 'created' // 새 키워드
| 'matched_exact' // 1단계: 정규화 해시 일치
| 'matched_trigram' // 2단계: 표기 변형/오타
| 'matched_vector' // 3단계: 의미 중복 → alias 흡수
| 'rejected_banned'; // 금칙어
export interface DedupResult {
action: DedupAction;
keywordId: string | null;
canonical: string;
matchedTo?: string;
similarity?: number;
}
export interface ResolveInput {
raw: string;
intent: KeywordIntent;
embedding: number[];
locale: string;
industryId: string | null;
regionId: string | null;
/** 새로 등록될 때 keyword.source — 매칭 후보 여부가 이 값으로 갈린다 */
source: string;
}
/** 4단계 계단식 중복제거. */
@Injectable()
export class DedupService {
private readonly logger = new Logger(DedupService.name);
constructor(private readonly repo: KeywordRepository) {}
async resolve(input: ResolveInput): Promise<DedupResult> {
const canonical = canonicalizeKeyword(input.raw);
const normalized = normalizeKeyword(input.raw);
// 0단계 — 금칙어/과장광고 차단
if (!normalized || isBanned(canonical)) {
return { action: 'rejected_banned', keywordId: null, canonical };
}
// 1단계 — 정규화 완전 일치 (공백/구두점 차이 흡수)
const exact = await this.repo.findByNormalized(normalized, input.locale);
if (exact) {
await this.repo.absorbAlias(exact.id, canonical);
return {
action: 'matched_exact',
keywordId: exact.id,
canonical: exact.canonical,
matchedTo: exact.canonical,
similarity: 1,
};
}
// 2~3단계 — trigram 후보 + 벡터 ANN 후보를 모아 최고 유사도 판정
const candidates = await this.repo.findDedupCandidates(
input.embedding,
normalized,
input.locale,
env.dedup.candidateLimit,
);
const trigramHit = candidates.find((c) => c.trg >= env.dedup.trigramThreshold);
if (trigramHit) {
await this.repo.absorbAlias(trigramHit.id, canonical);
return {
action: 'matched_trigram',
keywordId: trigramHit.id,
canonical: trigramHit.canonical,
matchedTo: trigramHit.canonical,
similarity: trigramHit.trg,
};
}
const best = candidates[0];
if (best && best.cosine >= env.dedup.cosineThreshold) {
await this.repo.absorbAlias(best.id, canonical);
return {
action: 'matched_vector',
keywordId: best.id,
canonical: best.canonical,
matchedTo: best.canonical,
similarity: best.cosine,
};
}
// 4단계 — 신규 등록
const created = await this.repo.insert({
canonical,
normalized,
locale: input.locale,
intent: input.intent,
embedding: input.embedding,
industryId: input.industryId,
regionId: input.regionId,
source: input.source,
});
return { action: 'created', keywordId: created.id, canonical: created.canonical };
}
}