[chore] docker-compose,ontology: 온톨로지를 이 레포로 들여 compose 한 벌로 띄운다 — 앱 Dockerfile 신설

발행이 SiteOntology 를 부르는데 서버는 따로 띄워야 했다. 실측(2026-09-14): 서버가 없으면
`[seo] SiteOntology 실패 — 키워드 없이 발행: ConnectError` 로 빌드는 성공하고 메타만 빈다 —
화면으로는 안 보이는 종류다. 한 벌로 묶어 "코드는 올라갔는데 서버가 없는" 상태를 없앤다.

- ontology/: gitea.o2o.kr/Web4ai/o2o-site-ontology 를 이 레포로 편입(그 원격은 그대로 남는다)
- ontology/Dockerfile(신규): 베이스는 node:22-slim. alpine 은 임베딩 런타임(onnxruntime)이
  musl 바이너리를 안 줘서 적재가 ERR_DLOPEN_FAILED 로 죽는다 — 빌드는 성공하고 실행에서만 터진다
- docker-compose.yml: ontology · ontology-postgres(pgvector) · ontology-redis 추가.
  자체 DB 를 쓰는 이유는 pgvector 확장 때문이다 — web4ai_db 를 남의 서비스 확장에 묶지 않는다
- 임베딩 모델(120MB)은 이미지에 굽지 않고 볼륨(ontology-model)에 남긴다
- 컨테이너끼리는 `http://ontology:3100` 으로 만난다. `.env` 의 127.0.0.1 은 컨테이너 자기 자신이라 안 닿는다

검증: 3개 기동 · 백엔드 컨테이너에서 ontology:3100/demo HTTP 200 · 마이그레이션·시드 완료

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-09-14 17:41:03 +09:00
1 parent bdc69a80f2
commit 01098835e9
70 files changed
+105484

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import { Controller, Get, Header } from '@nestjs/common';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
/** 로컬 확인용 매칭 데모 페이지. 빌드 산출물이 아니라 public/ 에서 직접 읽는다. */
@Controller()
export class DemoController {
@Get('demo')
@Header('content-type', 'text/html; charset=utf-8')
demo(): string {
return readFileSync(join(process.cwd(), 'public', 'demo.html'), 'utf8');
}
}
+182
View File
@@ -0,0 +1,182 @@
/**
* 매칭 규칙 테이블.
*
* 두 종류가 있다.
* · 서브 질의 빌더 — 프로필을 속성별로 쪼개 각각 임베딩한다 (통짜로 넣으면 속성이 희석된다)
* · 사실 기반 필터 — 벡터가 못 거르는 모순을 SQL/코드 조건으로 배제한다
* (임베딩은 "비슷함"만 알지 "최대 4인 < 단체"를 모른다)
*/
export interface MerchantFacts {
name: string;
region: string | null;
industry: string | null;
description: string;
address: string | null;
areaGroup: AreaGroup | null;
capacityMax: number | null;
services: string[];
features: string[];
audiences: string[];
nearby: string[];
amenities: Set<string>; // 정규화된 보유 시설
unverified: Set<string>; // 미확인 — 배제하지 않고 보류 처리
/** 고객 언어 — 인스타 해시태그, 리뷰 빈출어. 사업자가 쓰는 말과 다르므로 별도 레인으로 둔다 */
signals: string[];
}
export type AreaGroup = '해안·도서' | '원도심' | '시내';
export interface Lane {
key: string;
label: string;
weight: number;
text: string;
}
// ──────────────────────────────────────────── 권역 판정
const AREA_TERMS: Record<AreaGroup, string[]> = {
'해안·도서': ['선유도', '무녀도', '장자도', '대장도', '신시도', '야미도', '고군산군도', '새만금',
'비응항', '비응도', '오식도', '해수욕장', '몽돌', '오션뷰', '바다뷰', '해변', '섬'],
'원도심': ['원도심', '신흥동', '영화동', '월명', '말랭이마을', '동국사', '초원사진관', '이성당',
'경암동', '근대역사', '근대문화', '시간여행', '해망굴', '째보선창', '뜬다리', '일본식가옥'],
'시내': ['나운동', '수송동', '미룡동', '조촌동', '은파호수공원', '군산역', '시외버스'],
};
export function detectAreaGroup(text: string): AreaGroup | null {
const hits = (Object.entries(AREA_TERMS) as [AreaGroup, string[]][])
.map(([g, terms]) => [g, terms.filter((t) => text.includes(t)).length] as const)
.filter(([, n]) => n > 0)
.sort((a, b) => b[1] - a[1]);
return hits[0]?.[0] ?? null;
}
/** 키워드가 어느 권역에 속하는지 (해당 없으면 null = 권역 중립) */
export function keywordAreaGroup(keyword: string): AreaGroup | null {
return detectAreaGroup(keyword);
}
// ──────────────────────────────────────────── 수용 인원 모순
const GROUP_TERMS = ['단체', '워크샵', '워크숍', 'mt', '엠티', '20인', '15인', '10인',
'세미나', '단합', '대형', '펜션동', '전체대관'];
const GROUP_MIN_CAPACITY = 8;
export function violatesCapacity(keyword: string, capacityMax: number | null): boolean {
if (capacityMax === null || capacityMax >= GROUP_MIN_CAPACITY) return false;
const k = keyword.toLowerCase();
return GROUP_TERMS.some((t) => k.includes(t));
}
// ──────────────────────────────────────────── 시설 요구 조건
/** 키워드에 이 말이 있으면 해당 시설을 실제로 보유해야 한다 */
const AMENITY_REQUIRED: Array<[RegExp, string]> = [
[/바베큐|바비큐|바베큐장|그릴/, '바베큐'],
[/수영장|풀빌라|인피니티풀|온수풀|야외수영/, '수영장'],
[/스파|자쿠지|월풀|반신욕/, '스파'],
[/애견|반려|펫/, '애견동반'],
[/주차/, '주차'],
[/노래방/, '노래방'],
[/조식/, '조식'],
[/키즈룸|트램폴린/, '키즈시설'],
[/불멍|화로대|캠프파이어/, '불멍'],
[/빔프로젝터|넷플릭스/, '미디어'],
[/세미나실/, '세미나실'],
];
/** 시설 표기 흔들림을 통제 어휘로 모은다 */
const AMENITY_SYNONYMS: Array<[RegExp, string]> = [
[/바베큐|바비큐|그릴/, '바베큐'],
[/수영장|풀|풀빌라/, '수영장'],
[/스파|자쿠지|월풀|욕조/, '스파'],
[/애견|반려|펫/, '애견동반'],
[/주차/, '주차'],
[/노래방/, '노래방'],
[/조식|아침/, '조식'],
[/키즈|트램폴린|유아/, '키즈시설'],
[/불멍|화로|캠프파이어/, '불멍'],
[/넷플릭스|빔프로젝터|ott/i, '미디어'],
[/세미나/, '세미나실'],
];
export function normalizeAmenities(raw: string[]): Set<string> {
const out = new Set<string>();
for (const r of raw) {
for (const [re, canon] of AMENITY_SYNONYMS) if (re.test(r)) out.add(canon);
}
return out;
}
export type AmenityVerdict = { ok: true } | { ok: false; hold: boolean; amenity: string };
export function checkAmenity(keyword: string, facts: MerchantFacts): AmenityVerdict {
for (const [re, amenity] of AMENITY_REQUIRED) {
if (!re.test(keyword)) continue;
if (facts.amenities.has(amenity)) return { ok: true };
// 사업자가 확인해주지 않은 항목은 "없음"이 아니라 "모름" — 배제하지 않고 보류
const unverified = [...facts.unverified].some((u) =>
AMENITY_SYNONYMS.some(([sre, canon]) => canon === amenity && sre.test(u)));
return { ok: false, hold: unverified, amenity };
}
return { ok: true };
}
// ──────────────────────────────────────────── 서브 질의 빌더
const STAY_TYPE_HINTS = ['독채', '풀빌라', '스테이', '펜션', '글램핑', '카라반', '한옥', '민박', '감성'];
const CAPACITY_TOKEN = /\d+\s*인|기준|최대|소규모|중규모|대규모|수용/;
/**
* 레인 설계 원칙
* 1. 레인끼리 겹치지 않게 한다. 모든 레인에 "군산 펜션"을 넣으면 레인이 상관되고,
* 그러면 RRF 가 "여러 레인에 두루 걸린 generic 키워드"를 상위로 올린다.
* 지역+업종 앵커는 유형 레인에만 둔다.
* 2. 브랜드 레인은 두지 않는다. 상호는 사전에 없으므로 결국 "군산 펜션"만 남아
* 가장 generic 한 것들을 끌어온다 (실측에서 상위 6개가 전부 '~예약'으로 도배됐다).
* 3. 수용 인원은 레인에 넣지 않는다. 필터 전용이다.
*/
export function buildLanes(f: MerchantFacts): Lane[] {
const lanes: Lane[] = [];
// 토큰 단위로 중복을 제거한다. 문자열 단위 Set 만으로는 '신흥동' 과
// '신흥동 일본식가옥' 이 서로 다른 원소라 같은 낱말이 두 번 실리고,
// 그 낱말 쪽으로 레인이 쏠린다 (실제로 말랭이마을이 밀려났다).
const push = (key: string, label: string, weight: number, parts: (string | null | undefined)[]) => {
const seen = new Set<string>();
const words: string[] = [];
for (const part of parts) {
if (!part) continue;
for (const w of String(part).split(/\s+/)) {
const k = w.trim();
if (!k || seen.has(k)) continue;
seen.add(k);
words.push(k);
}
}
const text = words.join(' ');
if (text) lanes.push({ key, label, weight, text });
};
const isType = (x: string) => STAY_TYPE_HINTS.some((h) => x.includes(h));
const typeWords = [...f.features, ...f.services].filter(isType).slice(0, 3);
// 시설: 유형어·수용인원·권역어를 걷어낸 나머지 + 정규화된 보유 시설
const amenityWords = [
...f.amenities,
...f.features.filter((x) => !isType(x) && !CAPACITY_TOKEN.test(x) && !keywordAreaGroup(x)),
].slice(0, 6);
// 권역과 인근을 한 레인으로 합친다. 나눠 두면 '신흥동' 같은 토큰이 두 레인에 겹쳐
// 같은 위치 키워드가 두 번 가산되고, 상위가 전부 위치 키워드로 쓸려 나간다.
push('type', '유형', 1.0, [f.region, f.industry, ...typeWords]);
push('place', '위치', 0.7, [f.areaGroup, districtOf(f.address), ...f.nearby.slice(0, 4), '근처']);
push('audience', '동반자', 0.6, f.audiences.slice(0, 4));
push('amenity', '시설', 0.6, amenityWords);
// 고객 언어는 사업자 표현보다 검색어에 가깝다 — 데이터가 있으면 높게 잡는다
push('signal', '고객언어', 0.9, f.signals.slice(0, 10));
return lanes;
}
function districtOf(address: string | null): string | null {
if (!address) return null;
const m = address.match(/([가-힣]+(?:동|읍|면|리))/);
return m?.[1] ?? null;
}
+253
View File
@@ -0,0 +1,253 @@
import { Inject, Injectable } from '@nestjs/common';
import { Sql, toVector } from '../db/db';
import { PG } from '../db/db.module';
import { EmbeddingProvider } from '../embedding/types';
import { normalizeKeyword } from '../keywords/normalize';
import { MerchantWithTaxonomy } from '../merchants/merchants.service';
import {
AreaGroup, Lane, MerchantFacts, buildLanes, checkAmenity, detectAreaGroup,
keywordAreaGroup, normalizeAmenities, violatesCapacity,
} from './match.rules';
// RRF 상수를 관례값 60 대신 20 으로 낮춘다. 60 이면 1위와 40위의 기여도 차이가 1.6배뿐이라
// 깊은 순위의 generic 키워드가 여러 레인에서 조금씩 쌓아 상위를 차지한다. 20 이면 2.9배로 벌어진다.
const RRF_K = 20;
const LANE_DEPTH = 50; // 레인당 후보 깊이 — 깊을수록 generic 이 유리해진다
const LANE_FLOOR = 0.80; // 이 코사인 미만은 그 레인에서 기여하지 않는다
// 매칭 후보로 인정하는 출처. 고정 데이터셋 정책상 LLM 생성물은 사전에 섞이면 안 된다.
const MATCH_SOURCES = ['dataset', 'nationwide', 'manual'];
interface Hit {
id: string; canonical: string; intent: string; kind: string;
category: string | null; aliases: string[]; score: number;
}
export interface MatchRow extends Hit {
rrf: number;
status: 'ok' | 'hold';
holdReason?: string;
lanes: Array<{ key: string; label: string; rank: number; score: number }>;
linked: boolean;
}
@Injectable()
export class MatchService {
constructor(
@Inject(PG) private readonly sql: Sql,
private readonly embedder: EmbeddingProvider,
) {}
/** 속성별 서브 질의 → 가중 RRF 융합 → 사실 기반 필터 */
async fusion(rawQuery: string, limit: number) {
const query = rawQuery.trim();
const merchant = await this.resolveMerchant(query);
const facts = merchant ? toFacts(merchant) : null;
const lanes: Lane[] = facts
? buildLanes(facts)
: [{ key: 'free', label: '입력문', weight: 1.0, text: query }];
const vectors = await this.embedder.embed(lanes.map((l) => l.text), 'query');
// 레인별 검색.
// 후보 풀을 업체 업종으로 좁힌다. 사전 전체를 뒤지면 '강남 미용실' 같은
// 다른 업종 키워드가 후보에 섞인다 (실제로 섞여 있었다).
const perLane = await Promise.all(
vectors.map((v) => this.laneSearch(v, LANE_DEPTH, merchant?.industry_id ?? null)),
);
// 가중 RRF 융합
const acc = new Map<string, { hit: Hit; rrf: number; lanes: MatchRow['lanes'] }>();
perLane.forEach((hits, li) => {
const lane = lanes[li];
hits.forEach((hit, idx) => {
if (hit.score < LANE_FLOOR) return;
const rank = idx + 1;
const contrib = lane.weight / (RRF_K + rank);
const cur = acc.get(hit.id) ?? { hit, rrf: 0, lanes: [] };
cur.rrf += contrib;
cur.lanes.push({ key: lane.key, label: lane.label, rank, score: hit.score });
if (hit.score > cur.hit.score) cur.hit = hit;
acc.set(hit.id, cur);
});
});
// 사실 기반 필터
const kept: MatchRow[] = [];
const excluded: Array<{ canonical: string; reason: string }> = [];
for (const { hit, rrf, lanes: ls } of acc.values()) {
if (facts) {
if (violatesCapacity(hit.canonical, facts.capacityMax)) {
excluded.push({ canonical: hit.canonical, reason: `최대 ${facts.capacityMax}인 — 단체 키워드` });
continue;
}
const kwArea = keywordAreaGroup(hit.canonical);
if (kwArea && facts.areaGroup && kwArea !== facts.areaGroup) {
excluded.push({ canonical: hit.canonical, reason: `권역 불일치 — ${kwArea} (업체는 ${facts.areaGroup})` });
continue;
}
const am = checkAmenity(hit.canonical, facts);
if (!am.ok && !am.hold) {
excluded.push({ canonical: hit.canonical, reason: `미보유 시설 — ${am.amenity}` });
continue;
}
kept.push({
...hit, rrf,
lanes: ls.sort((a, b) => a.rank - b.rank),
status: am.ok ? 'ok' : 'hold',
holdReason: am.ok ? undefined : `${am.amenity} 미확인 — 사업자 확인 필요`,
linked: false,
});
} else {
kept.push({ ...hit, rrf, lanes: ls.sort((a, b) => a.rank - b.rank), status: 'ok', linked: false });
}
}
kept.sort((a, b) => b.rrf - a.rrf);
const top = kept.slice(0, limit);
// 레인별 상위 — SEO 페이지 배분은 평평한 순위가 아니라 이쪽을 쓴다.
// (주력 키워드는 유형 레인 1위, 주변 여행 페이지는 위치 레인 상위)
const keptById = new Map(kept.map((k) => [k.id, k]));
const byLane = lanes.map((lane, li) => ({
key: lane.key, label: lane.label, weight: lane.weight, text: lane.text,
items: perLane[li]
.map((h) => keptById.get(h.id))
.filter((x): x is MatchRow => Boolean(x))
.slice(0, 8),
}));
await this.markLinked([...top, ...byLane.flatMap((l) => l.items)], merchant?.id ?? null);
return {
mode: 'fusion' as const,
input: query,
resolved: merchant ? publicMerchant(merchant) : null,
facts: facts && {
areaGroup: facts.areaGroup,
capacityMax: facts.capacityMax,
amenities: [...facts.amenities],
unverified: [...facts.unverified],
},
lanes: lanes.map((l, i) => ({
...l, top: perLane[i][0]?.canonical ?? null, topScore: perLane[i][0]?.score ?? null,
})),
embeddingProvider: this.embedder.name,
total: await this.dictionarySize(),
matches: top,
byLane,
excluded: excluded.slice(0, 40),
excludedTotal: excluded.length,
};
}
private async laneSearch(
embedding: number[], limit: number, industryId: string | null,
): Promise<Hit[]> {
const vec = toVector(embedding);
const rows = await this.sql<Hit[]>`
SELECT id, canonical, intent, kind, category, aliases,
1 - (embedding <=> ${vec}::vector) AS score
FROM keyword
WHERE embedding IS NOT NULL
AND source = ANY(${MATCH_SOURCES})
AND (${industryId}::text IS NULL OR industry_id IS NULL OR industry_id = ${industryId})
ORDER BY embedding <=> ${vec}::vector
LIMIT ${limit}`;
return rows.map((r) => ({ ...r, score: Number(r.score) }));
}
private async markLinked(rows: MatchRow[], merchantId: string | null) {
if (!merchantId || rows.length === 0) return;
const ids = rows.map((r) => r.id);
const linked = await this.sql<Array<{ keyword_id: string }>>`
SELECT keyword_id FROM merchant_keyword
WHERE merchant_id = ${merchantId} AND keyword_id = ANY(${ids}::uuid[])`;
const set = new Set(linked.map((l) => l.keyword_id));
for (const r of rows) r.linked = set.has(r.id);
}
async resolveMerchant(query: string) {
const norm = normalizeKeyword(query);
if (!norm) return null;
const rows = await this.sql<Array<MerchantWithTaxonomy & { sim: number }>>`
SELECT m.*,
i.name AS industry_name, i.path::text AS industry_path,
r.name AS region_name, r.path::text AS region_path,
similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) AS sim
FROM merchant m
LEFT JOIN industry i ON i.id = m.industry_id
LEFT JOIN region r ON r.id = m.region_id
WHERE regexp_replace(lower(m.name), '\\s', '', 'g') = ${norm}
OR m.external_id = ${query}
OR similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) >= 0.45
ORDER BY sim DESC NULLS LAST
LIMIT 1`;
return rows[0] ?? null;
}
async dictionarySize() {
const [row] = await this.sql<Array<{ n: number }>>`
SELECT count(*)::int AS n FROM keyword
WHERE embedding IS NOT NULL AND source = ANY(${MATCH_SOURCES})`;
return row?.n ?? 0;
}
}
function str(v: unknown): string[] {
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
}
function toFacts(m: MerchantWithTaxonomy): MerchantFacts {
const p = (m.profile ?? {}) as Record<string, unknown>;
const features = str(p['features']);
const services = str(p['services']);
const nearby = str(p['nearby']);
const address = typeof p['address'] === 'string' ? p['address'] : null;
const cap = p['capacity'] as { max?: number } | undefined;
const areaSource = [address ?? '', ...nearby, m.description].join(' ');
const areaGroup: AreaGroup | null = detectAreaGroup(areaSource);
return {
name: m.name,
region: m.region_name,
industry: m.industry_name,
description: m.description,
address,
areaGroup,
capacityMax: typeof cap?.max === 'number' ? cap.max : null,
services, features,
audiences: str(p['audiences']),
nearby,
amenities: normalizeAmenities([...features, ...services]),
unverified: new Set(str(p['unverified'])),
signals: collectSignals(p),
};
}
/**
* 고객 언어 신호를 모은다.
* hashtags : ["#군산독채", "#군산감성숙소", ...] 인스타 등
* reviewSignals: [{ term: "바베큐", count: 47 }, ...] 리뷰 원문이 아닌 빈도 집계
* 리뷰 원문은 받지 않는다 (저작권·개인정보). 빈도만으로 충분하다.
*/
function collectSignals(p: Record<string, unknown>): string[] {
const tags = str(p['hashtags']).map((t) => t.replace(/^#/, '').trim()).filter(Boolean);
const raw = Array.isArray(p['reviewSignals']) ? p['reviewSignals'] : [];
const reviews = raw
.filter((r): r is { term: string; count: number } =>
Boolean(r) && typeof (r as any).term === 'string')
.sort((a, b) => (b.count ?? 0) - (a.count ?? 0))
.map((r) => r.term.trim())
.filter(Boolean);
return [...new Set([...reviews, ...tags])];
}
function publicMerchant(m: MerchantWithTaxonomy) {
return {
id: m.id, externalId: m.external_id, name: m.name,
region: m.region_name, industry: m.industry_name,
description: m.description, siteUrl: m.site_url, profile: m.profile ?? {},
};
}
@@ -0,0 +1,56 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { MatchService } from './match.service';
import { ServingService } from './serving.service';
@Controller('v1')
export class ServingController {
constructor(
private readonly serving: ServingService,
private readonly matcher: MatchService,
) {}
/** 발행된 사이트가 렌더링 시 호출 — SEO 메타 */
@Get('sites/:id/seo')
seo(@Param('id') id: string, @Query('limit') limit?: string) {
return this.serving.seo(id, clamp(limit, 20, 50));
}
/** 발행된 사이트가 렌더링 시 호출 — AEO(답변엔진) 소스 */
@Get('sites/:id/aeo')
aeo(@Param('id') id: string, @Query('limit') limit?: string) {
return this.serving.aeo(id, clamp(limit, 10, 30));
}
/** 어드민: 의미 기반 키워드 검색 */
@Post('keywords/search')
search(@Body() body: { query: string; limit?: number }) {
return this.serving.searchKeywords(body.query, Math.min(body.limit ?? 10, 50));
}
/**
* 자유 입력(업체명/문장) → 적재된 사전에서 잘 맞는 키워드.
* mode=fusion (기본) — 속성별 서브 질의 + 가중 RRF + 사실 기반 필터
* mode=single — 프로필을 통짜로 한 벡터에 넣는 이전 방식 (비교용)
*/
@Post('match')
match(@Body() body: { query: string; limit?: number; mode?: 'fusion' | 'single' }) {
const limit = Math.min(body.limit ?? 40, 200);
return body.mode === 'single'
? this.serving.match(body.query ?? '', limit)
: this.matcher.fusion(body.query ?? '', limit);
}
/** 성과 피드백 주입 (Search Console / 유입 로그) */
@Post('sites/:id/performance')
performance(
@Param('id') id: string,
@Body() body: { items: Array<{ keyword: string; impressions: number; clicks: number }> },
) {
return this.serving.applyPerformance(id, body.items ?? []);
}
}
function clamp(v: string | undefined, def: number, max: number): number {
const n = v ? Number(v) : def;
return Number.isFinite(n) ? Math.min(Math.max(1, n), max) : def;
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { KeywordsModule } from '../keywords/keywords.module';
import { MerchantsModule } from '../merchants/merchants.module';
import { DemoController } from './demo.controller';
import { MatchService } from './match.service';
import { ServingController } from './serving.controller';
import { ServingService } from './serving.service';
@Module({
imports: [MerchantsModule, KeywordsModule],
controllers: [ServingController, DemoController],
providers: [ServingService, MatchService],
})
export class ServingModule {}
+230
View File
@@ -0,0 +1,230 @@
import { Inject, Injectable } from '@nestjs/common';
import { PG } from '../db/db.module';
import { Sql, toVector } from '../db/db';
import { KeywordRepository } from '../keywords/keyword.repository';
import { normalizeKeyword } from '../keywords/normalize';
import { EmbeddingProvider } from '../embedding/types';
import { MerchantsService, MerchantWithTaxonomy } from '../merchants/merchants.service';
export interface SeoPayload {
merchant: { id: string; externalId: string; name: string; siteUrl: string | null };
title: string;
description: string;
keywords: string[];
tags: Array<{ keyword: string; intent: string; relevance: number; aliases: string[] }>;
generatedAt: string | null;
}
export interface AeoPayload {
merchant: { id: string; externalId: string; name: string };
topics: string[];
faqs: Array<{ question: string; answer: string }>;
/** JSON-LD 는 후속 단계에서 이 payload 를 그대로 매핑해 생성한다 */
structuredDataHints: {
type: 'LocalBusiness';
name: string;
description: string;
areaServed: string | null;
category: string | null;
};
}
@Injectable()
export class ServingService {
constructor(
@Inject(PG) private readonly sql: Sql,
private readonly merchants: MerchantsService,
private readonly keywords: KeywordRepository,
private readonly embedder: EmbeddingProvider,
) {}
async seo(idOrExternalId: string, limit: number): Promise<SeoPayload> {
const m = await this.merchants.findWithTaxonomy(idOrExternalId);
const rows = await this.sql<
Array<{ canonical: string; intent: string; relevance: number; aliases: string[] }>
>`
SELECT k.canonical, k.intent, mk.relevance, k.aliases
FROM merchant_keyword mk
JOIN keyword k ON k.id = mk.keyword_id
WHERE mk.merchant_id = ${m.id} AND mk.status = 'active'
ORDER BY mk.relevance DESC, k.usage_count ASC
LIMIT ${limit}`;
const kws = rows.map((r) => r.canonical);
const locality = [m.region_name, m.industry_name].filter(Boolean).join(' ');
return {
merchant: { id: m.id, externalId: m.external_id, name: m.name, siteUrl: m.site_url },
title: locality ? `${m.name} | ${locality}` : m.name,
description: buildDescription(m.name, m.description, kws),
keywords: kws,
tags: rows.map((r) => ({
keyword: r.canonical,
intent: r.intent,
relevance: Number(r.relevance),
aliases: r.aliases ?? [],
})),
generatedAt: m.last_generated_at ? new Date(m.last_generated_at).toISOString() : null,
};
}
async aeo(idOrExternalId: string, limit: number): Promise<AeoPayload> {
const m = await this.merchants.findWithTaxonomy(idOrExternalId);
const faqs = await this.sql<Array<{ question: string; answer: string }>>`
SELECT question, answer FROM qa_pair
WHERE merchant_id = ${m.id} AND status = 'active'
ORDER BY created_at ASC
LIMIT ${limit}`;
const topics = await this.sql<Array<{ canonical: string }>>`
SELECT k.canonical FROM merchant_keyword mk
JOIN keyword k ON k.id = mk.keyword_id
WHERE mk.merchant_id = ${m.id} AND mk.status = 'active'
AND k.intent IN ('informational', 'local')
ORDER BY mk.relevance DESC LIMIT ${limit}`;
return {
merchant: { id: m.id, externalId: m.external_id, name: m.name },
topics: topics.map((t) => t.canonical),
faqs,
structuredDataHints: {
type: 'LocalBusiness',
name: m.name,
description: m.description,
areaServed: m.region_name,
category: m.industry_name,
},
};
}
/**
* 자유 입력(업체명 또는 문장) → 적재된 키워드 사전에서 잘 맞는 것을 골라준다.
* 업체명이면 먼저 업체를 해석해 프로필 전체를 질의문으로 쓴다 —
* 상호만으로 임베딩하면 브랜드명 하나로 검색하는 것과 같아 매칭이 얕아진다.
*/
async match(rawQuery: string, limit: number) {
const query = rawQuery.trim();
const merchant = await this.resolveMerchant(query);
const queryText = merchant
? [
merchant.name,
merchant.region_name,
merchant.industry_name,
merchant.description,
...toStrings(merchant.profile?.['services']),
...toStrings(merchant.profile?.['features']),
...toStrings(merchant.profile?.['audiences']),
...toStrings(merchant.profile?.['nearby']),
].filter(Boolean).join(' ')
: query;
const [embedding] = await this.embedder.embed([queryText], 'query');
const rows = await this.sql<Array<{
id: string; canonical: string; intent: string; kind: string; category: string | null;
aliases: string[]; usage_count: number; score: number; linked: boolean;
}>>`
SELECT k.id, k.canonical, k.intent, k.kind, k.category, k.aliases, k.usage_count,
1 - (k.embedding <=> ${toVector(embedding)}::vector) AS score,
(mk.merchant_id IS NOT NULL) AS linked
FROM keyword k
LEFT JOIN merchant_keyword mk
ON mk.keyword_id = k.id AND mk.merchant_id = ${merchant?.id ?? null}
WHERE k.embedding IS NOT NULL
ORDER BY k.embedding <=> ${toVector(embedding)}::vector
LIMIT ${limit}`;
return {
mode: 'single' as const,
input: query,
resolved: merchant
? {
id: merchant.id, externalId: merchant.external_id, name: merchant.name,
region: merchant.region_name, industry: merchant.industry_name,
description: merchant.description, siteUrl: merchant.site_url,
profile: merchant.profile ?? {},
}
: null,
queryText,
embeddingProvider: this.embedder.name,
total: await this.dictionarySize(),
matches: rows.map((r) => ({ ...r, score: Number(r.score) })),
};
}
/** 상호는 띄어쓰기가 흔들린다 — 정규화 일치 → trigram 순으로 해석 */
private async resolveMerchant(query: string) {
const norm = normalizeKeyword(query);
if (!norm) return null;
const rows = await this.sql<Array<MerchantWithTaxonomy & { sim: number }>>`
SELECT m.*,
i.name AS industry_name, i.path::text AS industry_path,
r.name AS region_name, r.path::text AS region_path,
similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) AS sim
FROM merchant m
LEFT JOIN industry i ON i.id = m.industry_id
LEFT JOIN region r ON r.id = m.region_id
WHERE regexp_replace(lower(m.name), '\\s', '', 'g') = ${norm}
OR m.external_id = ${query}
OR similarity(regexp_replace(lower(m.name), '\\s', '', 'g'), ${norm}) >= 0.45
ORDER BY sim DESC NULLS LAST
LIMIT 1`;
return rows[0] ?? null;
}
async dictionarySize() {
const [row] = await this.sql<Array<{ n: number }>>`
SELECT count(*)::int AS n FROM keyword WHERE embedding IS NOT NULL`;
return row?.n ?? 0;
}
async searchKeywords(query: string, limit: number) {
const [embedding] = await this.embedder.embed([query], 'query');
return this.keywords.searchByVector(embedding, 'ko-KR', limit);
}
/** Search Console / 유입 로그 피드백 → 저성과 키워드 강등 */
async applyPerformance(
idOrExternalId: string,
items: Array<{ keyword: string; impressions: number; clicks: number }>,
) {
const m = await this.merchants.findWithTaxonomy(idOrExternalId);
let updated = 0;
for (const it of items) {
const rows = await this.sql<Array<{ keyword_id: string }>>`
UPDATE merchant_keyword mk
SET impressions = mk.impressions + ${it.impressions},
clicks = mk.clicks + ${it.clicks},
ctr = CASE WHEN (mk.impressions + ${it.impressions}) > 0
THEN (mk.clicks + ${it.clicks})::real / (mk.impressions + ${it.impressions})
ELSE 0 END,
updated_at = now()
FROM keyword k
WHERE k.id = mk.keyword_id
AND mk.merchant_id = ${m.id}
AND (k.canonical = ${it.keyword} OR ${it.keyword} = ANY(k.aliases))
RETURNING mk.keyword_id`;
updated += rows.length;
}
// 노출은 충분한데 클릭이 없는 키워드는 강등 → 다음 생성 사이클에서 대체
const demoted = await this.sql<Array<{ keyword_id: string }>>`
UPDATE merchant_keyword
SET status = 'demoted', updated_at = now()
WHERE merchant_id = ${m.id} AND status = 'active'
AND impressions >= 100 AND ctr < 0.002
RETURNING keyword_id`;
return { matched: updated, demoted: demoted.length };
}
}
function toStrings(v: unknown): string[] {
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
}
function buildDescription(name: string, desc: string, keywords: string[]): string {
const base = desc?.trim() || `${name} 안내`;
const tail = keywords.slice(0, 3).join(', ');
const full = tail ? `${base} ${tail} 정보를 확인하세요.` : base;
return full.length > 155 ? `${full.slice(0, 152)}...` : full;
}