[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

+36
View File
@@ -0,0 +1,36 @@
import { BullModule } from '@nestjs/bullmq';
import { Controller, Get, Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { env } from './config/env';
import { DbModule } from './db/db.module';
import { EmbeddingModule } from './embedding/embedding.module';
import { GenerationModule } from './generation/generation.module';
import { MerchantsHttpModule } from './merchants/merchants.controller.module';
import { ServingModule } from './serving/serving.module';
@Controller()
class HealthController {
@Get('health')
health() {
return {
status: 'ok',
llmProvider: env.llm.provider,
embeddingProvider: env.embedding.provider,
ts: new Date().toISOString(),
};
}
}
@Module({
imports: [
DbModule,
EmbeddingModule,
ScheduleModule.forRoot(),
BullModule.forRoot({ connection: { host: env.redis.host, port: env.redis.port } }),
GenerationModule,
MerchantsHttpModule,
ServingModule,
],
controllers: [HealthController],
})
export class AppModule {}
+34
View File
@@ -0,0 +1,34 @@
import 'dotenv/config';
const num = (v: string | undefined, d: number) => (v === undefined || v === '' ? d : Number(v));
export const env = {
port: num(process.env.PORT, 3100),
databaseUrl: process.env.DATABASE_URL ?? 'postgres://ontology:ontology@localhost:55432/ontology',
redis: {
host: process.env.REDIS_HOST ?? 'localhost',
port: num(process.env.REDIS_PORT, 56379),
},
llm: {
provider: (process.env.LLM_PROVIDER ?? 'mock') as 'mock' | 'openai',
apiKey: process.env.OPENAI_API_KEY ?? '',
model: process.env.OPENAI_MODEL ?? 'gpt-4.1-mini',
embeddingModel: process.env.OPENAI_EMBEDDING_MODEL ?? 'text-embedding-3-small',
},
embedding: {
provider: (process.env.EMBEDDING_PROVIDER ?? 'local') as 'mock' | 'local' | 'openai',
localModel: process.env.EMBEDDING_LOCAL_MODEL ?? 'Xenova/multilingual-e5-small',
},
dedup: {
cosineThreshold: num(process.env.DEDUP_COSINE_THRESHOLD, 0.99),
trigramThreshold: num(process.env.DEDUP_TRIGRAM_THRESHOLD, 0.6),
candidateLimit: num(process.env.DEDUP_CANDIDATE_LIMIT, 20),
},
generation: {
targetKeywords: num(process.env.GENERATION_TARGET_KEYWORDS, 15),
refreshIntervalDays: num(process.env.REFRESH_INTERVAL_DAYS, 30),
},
} as const;
export const EMBEDDING_DIM = 384;
export const PROMPT_VERSION = 'kw-v1';
+16
View File
@@ -0,0 +1,16 @@
import { Global, Module, OnModuleDestroy } from '@nestjs/common';
import { createSql, Sql } from './db';
export const PG = Symbol('PG');
@Global()
@Module({
providers: [{ provide: PG, useFactory: () => createSql() }],
exports: [PG],
})
export class DbModule implements OnModuleDestroy {
constructor() {}
async onModuleDestroy() {}
}
export type { Sql };
+17
View File
@@ -0,0 +1,17 @@
import postgres from 'postgres';
import { env } from '../config/env';
export type Sql = postgres.Sql<{}>;
export const createSql = (): Sql =>
postgres(env.databaseUrl, {
max: 10,
// pgvector 컬럼은 텍스트로 주고받는다 ('[0.1,0.2,...]')
transform: { undefined: null },
});
/** number[] -> pgvector 리터럴 */
export const toVector = (v: number[]): string => `[${v.join(',')}]`;
/** postgres.js 의 JSONValue 타입 제약 우회용 캐스트 */
export const asJson = (v: unknown) => v as Parameters<Sql['json']>[0];
+24
View File
@@ -0,0 +1,24 @@
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { createSql } from './db';
async function main() {
const sql = createSql();
const dir = join(process.cwd(), 'drizzle');
const files = readdirSync(dir).filter((f) => f.endsWith('.sql')).sort();
for (const file of files) {
const ddl = readFileSync(join(dir, file), 'utf8');
process.stdout.write(`▶ applying ${file} ... `);
await sql.unsafe(ddl);
process.stdout.write('done\n');
}
await sql.end();
console.log('✅ migration complete');
}
main().catch((e) => {
console.error('❌ migration failed:', e);
process.exit(1);
});
+119
View File
@@ -0,0 +1,119 @@
import { asJson, createSql } from './db';
const industries = [
['beauty', 'beauty', '뷰티'],
['beauty.hair', 'beauty.hair', '미용실'],
['beauty.nail', 'beauty.nail', '네일샵'],
['food', 'food', '음식점'],
['food.korean', 'food.korean', '한식당'],
['health', 'health', '의료'],
['health.dental', 'health.dental', '치과'],
['stay', 'stay', '숙박'],
['stay.pension', 'stay.pension', '펜션'],
];
const regions = [
['kr', 'kr', '대한민국'],
['kr.seoul', 'kr.seoul', '서울'],
['kr.seoul.gangnam', 'kr.seoul.gangnam', '강남'],
['kr.seoul.mapo', 'kr.seoul.mapo', '마포'],
['kr.busan', 'kr.busan', '부산'],
['kr.busan.haeundae', 'kr.busan.haeundae', '해운대'],
['kr.jeonbuk', 'kr.jeonbuk', '전북'],
['kr.jeonbuk.gunsan', 'kr.jeonbuk.gunsan', '군산'],
];
const merchants = [
{
externalId: 'site-1001',
name: '레브살롱',
industryId: 'beauty.hair',
regionId: 'kr.seoul.gangnam',
description: '강남역 3번 출구 앞 프라이빗 헤어살롱. 1:1 디자이너 전담 시스템.',
siteUrl: 'https://rev-salon.example.com',
profile: {
services: ['남자 커트', '여성 펌', '뿌리염색', '두피 클리닉'],
features: ['주차 가능', '심야 영업', '예약제'],
priceRange: '30,000~120,000원',
},
},
{
externalId: 'site-1002',
name: '헤어랩 강남점',
industryId: 'beauty.hair',
regionId: 'kr.seoul.gangnam',
description: '강남 대형 헤어샵. 염색과 클리닉 전문.',
siteUrl: 'https://hairlab.example.com',
profile: {
services: ['뿌리 염색', '여성 펌', '두피클리닉'],
features: ['주차가능', '단체 예약'],
priceRange: '25,000~150,000원',
},
},
{
externalId: 'site-2001',
name: '해운대 소담한상',
industryId: 'food.korean',
regionId: 'kr.busan.haeundae',
description: '해운대 해변 인근 한정식집. 제철 해산물 코스 제공.',
siteUrl: 'https://sodam.example.com',
profile: {
services: ['한정식 코스', '점심 특선', '단체 예약'],
features: ['오션뷰', '룸 완비', '발렛파킹'],
priceRange: '25,000~80,000원',
},
},
{
// 실제 업체. 공개 정보로 확인된 항목만 넣는다.
// 확인됨 : 상호, 군산 원도심(신흥동 말랭이마을 인근), 독채 2개 동, 기준 2인·최대 4인
// 미확인 : 가격, 바베큐/스파/주차/애견동반 여부 ← 사업자 확인 후 채울 것
externalId: 'site-3001',
name: '스테이머뭄',
industryId: 'stay.pension',
regionId: 'kr.jeonbuk.gunsan',
description:
'군산 원도심 말랭이마을 옆에 자리한 독채 스테이. A동·B동 두 채를 통째로 쓰며 기준 2인, 최대 4인.',
siteUrl: 'https://www.instagram.com/staymeomoom/',
profile: {
services: ['독채 대여', 'A동', 'B동'],
features: ['독채', '프라이빗', '2인 기준', '최대 4인', '원도심', '감성숙소'],
audiences: ['커플', '친구', '가족', '혼자'],
nearby: ['말랭이마을', '신흥동 일본식가옥', '동국사', '초원사진관', '이성당',
'경암동 철길마을', '근대역사박물관', '월명공원', '시간여행마을'],
address: '전북특별자치도 군산시 절골길 18 (신흥동)',
capacity: { standard: 2, max: 4 },
buildings: 2,
unverified: ['가격', '바베큐', '스파', '주차', '애견동반'],
},
},
];
async function main() {
const sql = createSql();
for (const [id, path, name] of industries) {
await sql`INSERT INTO industry (id, path, name) VALUES (${id}, ${path}::ltree, ${name})
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`;
}
for (const [id, path, name] of regions) {
await sql`INSERT INTO region (id, path, name) VALUES (${id}, ${path}::ltree, ${name})
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name`;
}
for (const m of merchants) {
await sql`
INSERT INTO merchant (external_id, name, industry_id, region_id, description, profile, site_url)
VALUES (${m.externalId}, ${m.name}, ${m.industryId}, ${m.regionId},
${m.description}, ${sql.json(asJson(m.profile))}, ${m.siteUrl})
ON CONFLICT (external_id) DO UPDATE SET
name = EXCLUDED.name, description = EXCLUDED.description,
profile = EXCLUDED.profile, updated_at = now()`;
}
await sql.end();
console.log(`✅ seed: industry=${industries.length} region=${regions.length} merchant=${merchants.length}`);
}
main().catch((e) => {
console.error('❌ seed failed:', e);
process.exit(1);
});
@@ -0,0 +1,19 @@
import { Global, Module } from '@nestjs/common';
import { env } from '../config/env';
import { LocalEmbeddingProvider } from './local.provider';
import { MockEmbeddingProvider } from './mock.provider';
import { OpenAiEmbeddingProvider } from './openai.provider';
import { EmbeddingProvider } from './types';
const IMPL = {
local: LocalEmbeddingProvider,
openai: OpenAiEmbeddingProvider,
mock: MockEmbeddingProvider,
} as const;
@Global()
@Module({
providers: [{ provide: EmbeddingProvider, useClass: IMPL[env.embedding.provider] }],
exports: [EmbeddingProvider],
})
export class EmbeddingModule {}
+48
View File
@@ -0,0 +1,48 @@
import { Injectable, Logger } from '@nestjs/common';
import { EMBEDDING_DIM, env } from '../config/env';
import { EmbedKind, EmbeddingProvider } from './types';
/** CommonJS 빌드에서 ESM 전용 패키지를 로드하기 위한 우회 (TS 가 require 로 바꾸지 못하게 한다) */
const esmImport = new Function('s', 'return import(s)') as (s: string) => Promise<any>;
/**
* 로컬 multilingual-e5-small (384차원, onnxruntime CPU).
* 최초 1회 모델을 내려받아 캐시하며 그 뒤로는 오프라인 동작한다.
*/
@Injectable()
export class LocalEmbeddingProvider extends EmbeddingProvider {
readonly name = 'local:multilingual-e5-small';
readonly dimensions = EMBEDDING_DIM;
private readonly logger = new Logger(LocalEmbeddingProvider.name);
private extractor: any | null = null;
private loading: Promise<any> | null = null;
private async pipe() {
if (this.extractor) return this.extractor;
if (!this.loading) {
this.loading = (async () => {
const t0 = Date.now();
const { pipeline } = await esmImport('@huggingface/transformers');
const fe = await pipeline('feature-extraction', env.embedding.localModel);
this.logger.log(`model ready: ${env.embedding.localModel} (${Date.now() - t0}ms)`);
this.extractor = fe;
return fe;
})();
}
return this.loading;
}
async embed(texts: string[], kind: EmbedKind = 'passage'): Promise<number[][]> {
if (texts.length === 0) return [];
const fe = await this.pipe();
const prefixed = texts.map((t) => `${kind}: ${t}`);
const out: number[][] = [];
const BATCH = 64;
for (let i = 0; i < prefixed.length; i += BATCH) {
const slice = prefixed.slice(i, i + BATCH);
const res = await fe(slice, { pooling: 'mean', normalize: true });
out.push(...(res.tolist() as number[][]));
}
return out;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Injectable } from '@nestjs/common';
import { EMBEDDING_DIM } from '../config/env';
import { hashEmbedding } from '../llm/mock.provider';
import { EmbedKind, EmbeddingProvider } from './types';
/** 모델 다운로드 없이 파이프라인을 돌리기 위한 문자 bigram 해싱 임베딩. 의미는 잡지 못한다. */
@Injectable()
export class MockEmbeddingProvider extends EmbeddingProvider {
readonly name = 'mock:bigram-hash';
readonly dimensions = EMBEDDING_DIM;
async embed(texts: string[], _kind: EmbedKind = 'passage'): Promise<number[][]> {
return texts.map((t) => hashEmbedding(t, EMBEDDING_DIM));
}
}
+21
View File
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import OpenAI from 'openai';
import { EMBEDDING_DIM, env } from '../config/env';
import { EmbedKind, EmbeddingProvider } from './types';
@Injectable()
export class OpenAiEmbeddingProvider extends EmbeddingProvider {
readonly name = `openai:${env.llm.embeddingModel}`;
readonly dimensions = EMBEDDING_DIM;
private readonly client = new OpenAI({ apiKey: env.llm.apiKey });
async embed(texts: string[], _kind: EmbedKind = 'passage'): Promise<number[][]> {
if (texts.length === 0) return [];
const res = await this.client.embeddings.create({
model: env.llm.embeddingModel,
input: texts,
dimensions: EMBEDDING_DIM, // 스키마와 차원을 맞춘다
});
return res.data.map((d) => d.embedding as number[]);
}
}
+8
View File
@@ -0,0 +1,8 @@
/** e5 계열은 query 와 passage 를 비대칭으로 인코딩한다 — 검색 품질에 직접 영향. */
export type EmbedKind = 'query' | 'passage';
export abstract class EmbeddingProvider {
abstract readonly name: string;
abstract readonly dimensions: number;
abstract embed(texts: string[], kind?: EmbedKind): Promise<number[][]>;
}
@@ -0,0 +1,20 @@
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { KeywordsModule } from '../keywords/keywords.module';
import { LlmModule } from '../llm/llm.module';
import { MerchantsModule } from '../merchants/merchants.module';
import { GenerationProcessor } from './generation.processor';
import { GENERATION_QUEUE, GenerationQueue } from './generation.queue';
import { GenerationService } from './generation.service';
@Module({
imports: [
BullModule.registerQueue({ name: GENERATION_QUEUE }),
LlmModule,
KeywordsModule,
MerchantsModule,
],
providers: [GenerationService, GenerationQueue, GenerationProcessor],
exports: [GenerationService, GenerationQueue],
})
export class GenerationModule {}
@@ -0,0 +1,21 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { GenerationService } from './generation.service';
import { GENERATION_QUEUE, GenerationJob } from './generation.queue';
@Processor(GENERATION_QUEUE, { concurrency: 2 })
export class GenerationProcessor extends WorkerHost {
private readonly logger = new Logger(GenerationProcessor.name);
constructor(private readonly generation: GenerationService) {
super();
}
async process(job: Job<GenerationJob>) {
const { merchantId, trigger } = job.data;
this.logger.log(`processing ${job.id} (${trigger})`);
const stats = await this.generation.runForMerchant(merchantId, trigger);
return { ...stats, details: undefined };
}
}
@@ -0,0 +1,50 @@
import { InjectQueue } from '@nestjs/bullmq';
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { Queue } from 'bullmq';
import { env } from '../config/env';
import { MerchantsService } from '../merchants/merchants.service';
import { GenerationTrigger } from './generation.service';
export const GENERATION_QUEUE = 'keyword-generation';
export interface GenerationJob {
merchantId: string;
trigger: GenerationTrigger;
}
@Injectable()
export class GenerationQueue {
private readonly logger = new Logger(GenerationQueue.name);
constructor(
@InjectQueue(GENERATION_QUEUE) private readonly queue: Queue<GenerationJob>,
private readonly merchants: MerchantsService,
) {}
async enqueue(merchantId: string, trigger: GenerationTrigger): Promise<string> {
// 짧은 시간 내 같은 업체가 여러 번 발행돼도 한 번만 처리 (60초 dedupe 창)
const job = await this.queue.add(
'generate',
{ merchantId, trigger },
{
deduplication: { id: `${merchantId}-${trigger}`, ttl: 60_000 },
removeOnComplete: 100,
removeOnFail: 500,
attempts: 3,
backoff: { type: 'exponential', delay: 5_000 },
},
);
return String(job.id);
}
/** 주기 리프레시: 매일 03:00, N일 지난 업체를 큐에 적재 */
@Cron(CronExpression.EVERY_DAY_AT_3AM)
async scheduleRefresh() {
const stale = await this.merchants.findStale(env.generation.refreshIntervalDays, 200);
for (const m of stale) {
await this.enqueue(m.id, 'scheduled');
}
if (stale.length) this.logger.log(`scheduled refresh queued: ${stale.length} merchants`);
}
}
@@ -0,0 +1,216 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import { PG } from '../db/db.module';
import { asJson, Sql, toVector } from '../db/db';
import { env, PROMPT_VERSION } from '../config/env';
import { DedupAction, DedupService } from '../keywords/dedup.service';
import { canonicalizeKeyword, normalizeKeyword } from '../keywords/normalize';
import { EmbeddingProvider } from '../embedding/types';
import { LlmProvider, MerchantContext } from '../llm/types';
import { MerchantsService } from '../merchants/merchants.service';
export type GenerationTrigger = 'published' | 'scheduled' | 'manual';
export interface GenerationStats {
runId: string;
merchantId: string;
merchantName: string;
provider: string;
model: string;
candidates: number;
created: number;
matchedExact: number;
matchedTrigram: number;
matchedVector: number;
rejected: number;
linked: number;
qaCreated: number;
durationMs: number;
details: Array<{ candidate: string; action: DedupAction; matchedTo?: string; similarity?: number }>;
}
@Injectable()
export class GenerationService {
private readonly logger = new Logger(GenerationService.name);
constructor(
@Inject(PG) private readonly sql: Sql,
private readonly merchants: MerchantsService,
private readonly llm: LlmProvider,
private readonly embedder: EmbeddingProvider,
private readonly dedup: DedupService,
) {}
async runForMerchant(
idOrExternalId: string,
trigger: GenerationTrigger = 'manual',
targetCount = env.generation.targetKeywords,
): Promise<GenerationStats> {
const startedAt = Date.now();
const merchant = await this.merchants.findWithTaxonomy(idOrExternalId);
const runRows = await this.sql<Array<{ id: string }>>`
INSERT INTO generation_run (merchant_id, provider, model, prompt_version, trigger, status, input)
VALUES (${merchant.id}, ${this.llm.name}, ${this.llm.model}, ${PROMPT_VERSION},
${trigger}, 'running', ${this.sql.json(asJson({ externalId: merchant.external_id }))})
RETURNING id`;
const runId = runRows[0].id;
try {
const existing = await this.existingKeywordsFor(merchant.id, merchant.industry_id);
const ctx: MerchantContext = {
externalId: merchant.external_id,
name: merchant.name,
description: merchant.description,
industryName: merchant.industry_name,
industryPath: merchant.industry_path,
regionName: merchant.region_name,
regionPath: merchant.region_path,
profile: merchant.profile ?? {},
existingKeywords: existing,
targetCount,
};
const output = await this.llm.generate(ctx);
// 임베딩은 한 번에 배치 호출 (후보 수만큼 왕복하지 않는다)
const texts = output.keywords.map((k) => canonicalizeKeyword(k.keyword));
const embeddings = texts.length ? await this.embedder.embed(texts, 'passage') : [];
const stats: GenerationStats = {
runId,
merchantId: merchant.id,
merchantName: merchant.name,
provider: this.llm.name,
model: output.model,
candidates: output.keywords.length,
created: 0,
matchedExact: 0,
matchedTrigram: 0,
matchedVector: 0,
rejected: 0,
linked: 0,
qaCreated: 0,
durationMs: 0,
details: [],
};
for (let i = 0; i < output.keywords.length; i++) {
const cand = output.keywords[i];
const result = await this.dedup.resolve({
raw: cand.keyword,
intent: cand.intent,
embedding: embeddings[i],
locale: 'ko-KR',
industryId: merchant.industry_id,
regionId: merchant.region_id,
});
stats.details.push({
candidate: canonicalizeKeyword(cand.keyword),
action: result.action,
matchedTo: result.matchedTo,
similarity: result.similarity,
});
switch (result.action) {
case 'created': stats.created++; break;
case 'matched_exact': stats.matchedExact++; break;
case 'matched_trigram': stats.matchedTrigram++; break;
case 'matched_vector': stats.matchedVector++; break;
case 'rejected_banned': stats.rejected++; break;
}
if (result.keywordId) {
const linked = await this.linkKeyword(merchant.id, result.keywordId, cand.relevance, cand.rationale);
if (linked) stats.linked++;
}
}
stats.qaCreated = await this.upsertQaPairs(merchant.id, output.qaPairs);
await this.merchants.markGenerated(merchant.id);
stats.durationMs = Date.now() - startedAt;
await this.sql`
UPDATE generation_run
SET status = 'succeeded',
output = ${this.sql.json(asJson(output))},
stats = ${this.sql.json(asJson({ ...stats, details: undefined }))},
finished_at = now()
WHERE id = ${runId}`;
this.logger.log(
`[${merchant.name}] cand=${stats.candidates} new=${stats.created} ` +
`dup(exact/trg/vec)=${stats.matchedExact}/${stats.matchedTrigram}/${stats.matchedVector} ` +
`rejected=${stats.rejected} qa=${stats.qaCreated} ${stats.durationMs}ms`,
);
return stats;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
await this.sql`
UPDATE generation_run
SET status = 'failed', error = ${message}, finished_at = now()
WHERE id = ${runId}`;
throw err;
}
}
/** 프롬프트에 넣을 "이미 보유한 키워드": 자기 것 + 같은 업종에서 많이 쓰는 것 */
private async existingKeywordsFor(merchantId: string, industryId: string | null): Promise<string[]> {
const rows = await this.sql<Array<{ canonical: string }>>`
SELECT DISTINCT k.canonical
FROM keyword k
LEFT JOIN merchant_keyword mk ON mk.keyword_id = k.id AND mk.merchant_id = ${merchantId}
WHERE mk.merchant_id IS NOT NULL
OR (${industryId}::text IS NOT NULL AND k.industry_id = ${industryId} AND k.usage_count > 0)
ORDER BY k.canonical
LIMIT 100`;
return rows.map((r) => r.canonical);
}
private async linkKeyword(
merchantId: string,
keywordId: string,
relevance: number,
rationale: string,
): Promise<boolean> {
const status = relevance >= 0.5 ? 'active' : 'candidate';
const rows = await this.sql<Array<{ inserted: boolean }>>`
INSERT INTO merchant_keyword (merchant_id, keyword_id, relevance, source, status, rationale)
VALUES (${merchantId}, ${keywordId}, ${relevance}, 'llm', ${status}, ${rationale})
ON CONFLICT (merchant_id, keyword_id) DO UPDATE SET
relevance = GREATEST(merchant_keyword.relevance, EXCLUDED.relevance),
rationale = COALESCE(EXCLUDED.rationale, merchant_keyword.rationale),
updated_at = now()
RETURNING (xmax = 0) AS inserted`;
if (rows[0]?.inserted) {
await this.sql`UPDATE keyword SET usage_count = usage_count + 1 WHERE id = ${keywordId}`;
return true;
}
return false;
}
private async upsertQaPairs(
merchantId: string,
pairs: Array<{ question: string; answer: string }>,
): Promise<number> {
if (pairs.length === 0) return 0;
const embeddings = await this.embedder.embed(pairs.map((p) => p.question), 'passage');
let created = 0;
for (let i = 0; i < pairs.length; i++) {
const p = pairs[i];
const nq = normalizeKeyword(p.question);
if (!nq) continue;
const rows = await this.sql<Array<{ inserted: boolean }>>`
INSERT INTO qa_pair (merchant_id, question, answer, normalized_question, embedding)
VALUES (${merchantId}, ${canonicalizeKeyword(p.question)}, ${p.answer.trim()},
${nq}, ${toVector(embeddings[i])}::vector)
ON CONFLICT (merchant_id, normalized_question) DO UPDATE SET
answer = EXCLUDED.answer, updated_at = now()
RETURNING (xmax = 0) AS inserted`;
if (rows[0]?.inserted) created++;
}
return created;
}
}
+113
View File
@@ -0,0 +1,113 @@
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;
}
/**
* 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 후보를 모아 최고 유사도 판정
//
// 주의: 짧은 한글 키워드에서는 문장 임베딩의 절대 코사인이 변별력이 약하다.
// 실측(multilingual-e5-small): '선유도 펜션' ↔ '새만금 펜션' = 0.936,
// '군산 펜션' ↔ '군산 호텔' = 0.970 — 전혀 다른 키워드인데도 높게 나온다.
// 반면 어순만 바뀐 진짜 중복('군산 키즈룸 펜션' ↔ '군산 펜션 키즈룸')은 0.999 대에 몰린다.
// 그래서 임계값을 0.99 로 올려 잡고, 자동 병합의 주력은 1~2단계(어휘)에 둔다.
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,
});
return { action: 'created', keywordId: created.id, canonical: created.canonical };
}
}
+124
View File
@@ -0,0 +1,124 @@
import { Inject, Injectable } from '@nestjs/common';
import { PG } from '../db/db.module';
import { Sql, toVector } from '../db/db';
import { KeywordIntent } from '../llm/types';
export interface KeywordRow {
id: string;
canonical: string;
normalized: string;
aliases: string[];
intent: KeywordIntent;
usage_count: number;
}
export interface CandidateRow {
id: string;
canonical: string;
normalized: string;
cosine: number;
trg: number;
}
@Injectable()
export class KeywordRepository {
constructor(@Inject(PG) private readonly sql: Sql) {}
async findByNormalized(normalized: string, locale: string): Promise<KeywordRow | null> {
const rows = await this.sql<KeywordRow[]>`
SELECT id, canonical, normalized, aliases, intent, usage_count
FROM keyword
WHERE normalized = ${normalized} AND locale = ${locale}
LIMIT 1`;
return rows[0] ?? null;
}
/**
* 중복 후보 수집: trigram 인덱스 히트 + 벡터 ANN 상위 N 을 합집합으로 가져온다.
* 벡터 비교는 이 후보 집합 안에서만 하므로 전수 비교가 일어나지 않는다.
*/
async findDedupCandidates(
embedding: number[],
normalized: string,
locale: string,
limit: number,
): Promise<CandidateRow[]> {
const vec = toVector(embedding);
const rows = await this.sql<CandidateRow[]>`
(
SELECT id, canonical, normalized,
1 - (embedding <=> ${vec}::vector) AS cosine,
similarity(normalized, ${normalized}) AS trg
FROM keyword
WHERE locale = ${locale}
AND embedding IS NOT NULL
AND normalized % ${normalized}
ORDER BY trg DESC
LIMIT ${limit}
)
UNION ALL
(
SELECT id, canonical, normalized,
1 - (embedding <=> ${vec}::vector) AS cosine,
0::real AS trg
FROM keyword
WHERE locale = ${locale}
AND embedding IS NOT NULL
ORDER BY embedding <=> ${vec}::vector
LIMIT ${limit}
)`;
const best = new Map<string, CandidateRow>();
for (const r of rows) {
const prev = best.get(r.id);
if (!prev || r.trg > prev.trg) best.set(r.id, { ...r, cosine: Number(r.cosine), trg: Number(r.trg) });
}
return [...best.values()].sort((a, b) => b.cosine - a.cosine);
}
async insert(input: {
canonical: string;
normalized: string;
locale: string;
intent: KeywordIntent;
embedding: number[];
industryId: string | null;
regionId: string | null;
}): Promise<KeywordRow> {
const rows = await this.sql<KeywordRow[]>`
INSERT INTO keyword (canonical, normalized, locale, intent, embedding, industry_id, region_id, usage_count)
VALUES (${input.canonical}, ${input.normalized}, ${input.locale}, ${input.intent},
${toVector(input.embedding)}::vector, ${input.industryId}, ${input.regionId}, 0)
ON CONFLICT (normalized, locale) DO UPDATE SET updated_at = now()
RETURNING id, canonical, normalized, aliases, intent, usage_count`;
return rows[0];
}
/** 표기 변형을 기존 키워드에 흡수 (롱테일 검색어 보존) */
async absorbAlias(keywordId: string, alias: string): Promise<void> {
await this.sql`
UPDATE keyword
SET aliases = (
SELECT ARRAY(SELECT DISTINCT unnest(aliases || ARRAY[${alias}]::text[]))
),
updated_at = now()
WHERE id = ${keywordId}
AND NOT (${alias} = ANY(aliases))
AND canonical <> ${alias}`;
}
async bumpUsage(keywordId: string): Promise<void> {
await this.sql`
UPDATE keyword SET usage_count = usage_count + 1, updated_at = now() WHERE id = ${keywordId}`;
}
async searchByVector(embedding: number[], locale: string, limit: number) {
const vec = toVector(embedding);
return this.sql<Array<{ id: string; canonical: string; intent: string; usage_count: number; score: number }>>`
SELECT id, canonical, intent, usage_count, 1 - (embedding <=> ${vec}::vector) AS score
FROM keyword
WHERE locale = ${locale} AND embedding IS NOT NULL
ORDER BY embedding <=> ${vec}::vector
LIMIT ${limit}`;
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { DedupService } from './dedup.service';
import { KeywordRepository } from './keyword.repository';
@Module({
providers: [KeywordRepository, DedupService],
exports: [KeywordRepository, DedupService],
})
export class KeywordsModule {}
+33
View File
@@ -0,0 +1,33 @@
/**
* 중복 판정용 정규화.
* NFKC → 소문자 → 제로폭 문자 제거 → 구두점 제거 → 공백 전부 제거.
* "강남 미용실" 과 "강남미용실" 을 같은 키로 취급하기 위해 공백을 없앤다.
*/
const ZERO_WIDTH = /[\u200B-\u200D\uFEFF]/g;
const PUNCT = /[!-\/:-@\[-`{-~·ㆍ、。「-』]/g;
export function normalizeKeyword(raw: string): string {
return raw
.normalize('NFKC')
.toLowerCase()
.replace(ZERO_WIDTH, '')
.replace(PUNCT, '')
.replace(/\s+/g, '');
}
/** 표시용 정리: 앞뒤/중복 공백만 정리하고 원문 표기는 보존 */
export function canonicalizeKeyword(raw: string): string {
return raw.normalize('NFKC').replace(ZERO_WIDTH, '').replace(/\s+/g, ' ').trim();
}
/** 과장광고·금칙 표현 필터 (광고심의 리스크 차단) */
const BANNED = [
'최고', '1위', '일등', '넘버원', 'no.1', '100%', '무조건', '완치', '부작용없',
'영구', '평생보장', '유일한', '최저가보장', '전국최대',
];
const BANNED_NORMALIZED = BANNED.map(normalizeKeyword);
export function isBanned(text: string): boolean {
const n = normalizeKeyword(text);
return BANNED_NORMALIZED.some((b) => b.length > 0 && n.includes(b));
}
+16
View File
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { env } from '../config/env';
import { MockLlmProvider } from './mock.provider';
import { OpenAiLlmProvider } from './openai.provider';
import { LlmProvider } from './types';
@Module({
providers: [
{
provide: LlmProvider,
useClass: env.llm.provider === 'openai' ? OpenAiLlmProvider : MockLlmProvider,
},
],
exports: [LlmProvider],
})
export class LlmModule {}
+160
View File
@@ -0,0 +1,160 @@
import { Injectable } from '@nestjs/common';
import { EMBEDDING_DIM } from '../config/env';
import { normalizeKeyword } from '../keywords/normalize';
import {
GenerationOutput,
KeywordCandidate,
KeywordIntent,
LlmProvider,
MerchantContext,
QaCandidate,
} from './types';
/**
* API 키 없이 로컬에서 전체 파이프라인(생성 → 중복제거 → 서빙)을 돌리기 위한 대체 구현.
*
* embed(): 문자 bigram 해싱 + L2 정규화.
* 랜덤이 아니라 "비슷한 문자열이면 비슷한 벡터"가 나오므로
* 코사인 임계값 기반 중복제거 동작을 실제와 유사하게 검증할 수 있다.
*/
@Injectable()
export class MockLlmProvider extends LlmProvider {
readonly name = 'mock';
readonly model = 'mock-keyword-v1';
async generate(ctx: MerchantContext): Promise<GenerationOutput> {
const region = ctx.regionName ?? '';
const industry = ctx.industryName ?? '업체';
const p = ctx.profile;
const services = toStringArray(p['services']);
const features = toStringArray(p['features']);
const audiences = toStringArray(p['audiences']);
const nearby = toStringArray(p['nearby']);
const seasons = toStringArray(p['seasons']);
const MODIFIERS = ['추천', '예약', '가격', '후기', '저렴한곳', '깨끗한', '인기', '순위', '위치', '실시간예약'];
const out: Array<[string, KeywordIntent, number]> = [];
const push = (k: string, intent: KeywordIntent, rel: number) => out.push([k, intent, rel]);
// 실제 로컬 검색 패턴을 프로필 배열의 조합으로 전개한다.
push(ctx.name, 'brand', 0.99);
push(`${region} ${ctx.name}`, 'brand', 0.97);
push(`${region} ${industry}`, 'local', 0.95);
push(`${region} ${industry} 추천`, 'local', 0.93);
for (const m of MODIFIERS) {
push(`${region} ${industry} ${m}`, intentOf(m), 0.86);
}
for (const a of audiences) {
push(`${region} ${a} ${industry}`, 'local', 0.88);
for (const m of MODIFIERS.slice(0, 4)) push(`${region} ${a} ${industry} ${m}`, intentOf(m), 0.74);
push(`${a} ${industry} 추천`, 'informational', 0.62);
}
for (const f of features) {
push(`${region} ${f} ${industry}`, 'local', 0.84);
push(`${industry} ${f}`, 'informational', 0.6);
push(`${region} ${industry} ${f}`, 'local', 0.7);
}
for (const s of services) {
push(`${region} ${s}`, 'local', 0.82);
for (const m of MODIFIERS.slice(0, 4)) push(`${s} ${m}`, intentOf(m), 0.66);
}
for (const n of nearby) {
push(`${n} 근처 ${industry}`, 'local', 0.8);
push(`${n} ${industry} 추천`, 'local', 0.76);
push(`${n} 숙소`, 'local', 0.68);
}
for (const s of seasons) {
push(`${s} ${region} ${industry}`, 'local', 0.72);
push(`${region} ${s} ${industry} 예약`, 'transactional', 0.64);
}
// 동반자 × 시설 롱테일 — 여기서부터 검색량이 급격히 얇아진다
for (const a of audiences) {
for (const f of features) push(`${region} ${a} ${f} ${industry}`, 'local', 0.42);
}
for (const a of audiences) {
for (const s of services) push(`${a} ${s}`, 'informational', 0.38);
}
// 질문형 (AEO 유입)
for (const a of audiences) push(`${region} ${a} ${industry} 어디가 좋을까요`, 'informational', 0.5);
for (const n of nearby) push(`${n} 여행 ${industry} 어디`, 'informational', 0.44);
const seen = new Set<string>();
const keywords: KeywordCandidate[] = [];
for (const [raw, intent, relevance] of out) {
const k = raw.replace(/\s+/g, ' ').trim();
if (!k || seen.has(k)) continue;
seen.add(k);
keywords.push({ keyword: k, intent, relevance, rationale: `mock: ${intent}` });
if (keywords.length >= ctx.targetCount) break;
}
const qaPairs: QaCandidate[] = [
{
question: `${ctx.name}은(는) 어디에 있나요?`,
answer: `${ctx.name}은(는) ${region || '해당 지역'}에 위치한 ${industry}입니다.`,
},
{
question: `${ctx.name} 예약은 어떻게 하나요?`,
answer: `${ctx.name}은(는) 사이트 예약 페이지 또는 전화로 예약할 수 있습니다.`,
},
{
question: `${ctx.name}의 주요 서비스는 무엇인가요?`,
answer: services.length
? `주요 서비스는 ${services.join(', ')} 입니다.`
: `${industry} 관련 서비스를 제공합니다.`,
},
{
question: `${ctx.name} 근처에 가볼 만한 곳은 어디인가요?`,
answer: nearby.length
? `${nearby.join(', ')} 등이 가깝습니다.`
: `${region} 주요 명소가 인근에 있습니다.`,
},
{
question: `${ctx.name}에 ${audiences[0] ?? '반려동물'}도 갈 수 있나요?`,
answer: features.length
? `${features.join(', ')} 조건을 제공합니다. 예약 전 상세 조건을 확인해 주세요.`
: `예약 전 상세 조건을 확인해 주세요.`,
},
];
return { keywords, qaPairs, model: this.model, provider: this.name };
}
}
function intentOf(modifier: string): KeywordIntent {
if (modifier === '예약' || modifier === '실시간예약' || modifier === '가격') return 'transactional';
if (modifier === '후기' || modifier === '순위') return 'informational';
return 'local';
}
function toStringArray(v: unknown): string[] {
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
}
/** 문자 bigram 해싱 임베딩 (결정적, L2 정규화) */
export function hashEmbedding(text: string, dim = EMBEDDING_DIM): number[] {
const s = ` ${normalizeKeyword(text)} `;
const vec = new Float64Array(dim);
for (let i = 0; i < s.length - 1; i++) {
const gram = s.slice(i, i + 2);
const h = fnv1a(gram);
vec[h % dim] += 1;
// 부호 해싱으로 충돌 편향 완화
vec[(h >>> 8) % dim] += h & 1 ? 1 : -1;
}
let norm = 0;
for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];
norm = Math.sqrt(norm) || 1;
return Array.from(vec, (x) => x / norm);
}
function fnv1a(str: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h >>> 0;
}
+114
View File
@@ -0,0 +1,114 @@
import { Injectable, Logger } from '@nestjs/common';
import OpenAI from 'openai';
import { env } from '../config/env';
import { GenerationOutput, LlmProvider, MerchantContext } from './types';
/** Structured Outputs 로 강제하는 응답 스키마 — 자유 텍스트 파싱 금지 */
const RESPONSE_SCHEMA = {
type: 'object',
additionalProperties: false,
required: ['keywords', 'qa_pairs'],
properties: {
keywords: {
type: 'array',
items: {
type: 'object',
additionalProperties: false,
required: ['keyword', 'intent', 'relevance', 'rationale'],
properties: {
keyword: { type: 'string' },
intent: {
type: 'string',
enum: ['informational', 'navigational', 'transactional', 'local', 'brand'],
},
relevance: { type: 'number' },
rationale: { type: 'string' },
},
},
},
qa_pairs: {
type: 'array',
items: {
type: 'object',
additionalProperties: false,
required: ['question', 'answer'],
properties: {
question: { type: 'string' },
answer: { type: 'string' },
},
},
},
},
} as const;
@Injectable()
export class OpenAiLlmProvider extends LlmProvider {
readonly name = 'openai';
readonly model = env.llm.model;
private readonly logger = new Logger(OpenAiLlmProvider.name);
private readonly client = new OpenAI({ apiKey: env.llm.apiKey });
async generate(ctx: MerchantContext): Promise<GenerationOutput> {
const res = await this.client.chat.completions.create({
model: this.model,
temperature: 0.7,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: buildUserPrompt(ctx) },
],
response_format: {
type: 'json_schema',
json_schema: { name: 'seo_aeo_keywords', strict: true, schema: RESPONSE_SCHEMA as any },
},
});
const content = res.choices[0]?.message?.content ?? '{}';
const parsed = JSON.parse(content) as {
keywords?: GenerationOutput['keywords'];
qa_pairs?: GenerationOutput['qaPairs'];
};
return {
keywords: parsed.keywords ?? [],
qaPairs: parsed.qa_pairs ?? [],
model: this.model,
provider: this.name,
usage: {
prompt_tokens: res.usage?.prompt_tokens ?? 0,
completion_tokens: res.usage?.completion_tokens ?? 0,
total_tokens: res.usage?.total_tokens ?? 0,
},
};
}
}
const SYSTEM_PROMPT = `당신은 한국 로컬 비즈니스 SEO/AEO 전문가입니다.
주어진 업체 정보를 바탕으로 검색 유입에 실제로 도움이 되는 키워드와,
답변엔진(AI 검색)이 인용하기 좋은 질문-답변 쌍을 생성합니다.
규칙:
- 실제 사용자가 검색창에 입력할 법한 자연스러운 한국어 표현만 사용합니다.
- 지역명 + 업종 + 의도어 조합을 적극 활용합니다.
- 과장광고 표현(최고, 1위, 100%, 무조건, 완치 등)은 절대 사용하지 않습니다.
- 제공된 "이미 보유한 키워드"와 의미가 겹치는 것은 생성하지 않습니다.
- relevance 는 해당 업체와의 관련도를 0.0~1.0 으로 매깁니다.
- 답변(answer)은 2~3문장, 업체 정보에 근거한 사실만 씁니다.`;
function buildUserPrompt(ctx: MerchantContext): string {
return [
`# 업체 정보`,
`- 상호: ${ctx.name}`,
`- 업종: ${ctx.industryName ?? '미상'} (${ctx.industryPath ?? '-'})`,
`- 지역: ${ctx.regionName ?? '미상'} (${ctx.regionPath ?? '-'})`,
`- 소개: ${ctx.description || '없음'}`,
`- 상세: ${JSON.stringify(ctx.profile, null, 2)}`,
``,
`# 이미 보유한 키워드 (이것들과 겹치지 않는 새 후보만 생성)`,
ctx.existingKeywords.length ? ctx.existingKeywords.map((k) => `- ${k}`).join('\n') : '- (없음)',
``,
`# 요청`,
`- 키워드 ${ctx.targetCount}개`,
`- 질문-답변 쌍 5개`,
].join('\n');
}
+46
View File
@@ -0,0 +1,46 @@
export type KeywordIntent =
| 'informational'
| 'navigational'
| 'transactional'
| 'local'
| 'brand';
export interface MerchantContext {
externalId: string;
name: string;
description: string;
industryName?: string | null;
industryPath?: string | null;
regionName?: string | null;
regionPath?: string | null;
profile: Record<string, unknown>;
/** 이미 보유한 키워드 — 프롬프트에 넣어 중복 후보 생성 자체를 줄인다 */
existingKeywords: string[];
targetCount: number;
}
export interface KeywordCandidate {
keyword: string;
intent: KeywordIntent;
relevance: number; // 0..1
rationale: string;
}
export interface QaCandidate {
question: string;
answer: string;
}
export interface GenerationOutput {
keywords: KeywordCandidate[];
qaPairs: QaCandidate[];
model: string;
provider: string;
usage?: Record<string, number>;
}
export abstract class LlmProvider {
abstract readonly name: string;
abstract readonly model: string;
abstract generate(ctx: MerchantContext): Promise<GenerationOutput>;
}
+17
View File
@@ -0,0 +1,17 @@
import 'reflect-metadata';
import { Logger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { env } from './config/env';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
app.enableCors();
await app.listen(env.port);
new Logger('bootstrap').log(
`o2o-site-ontology listening on http://localhost:${env.port} (llm=${env.llm.provider})`,
);
}
bootstrap();
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { GenerationModule } from '../generation/generation.module';
import { MerchantsController } from './merchants.controller';
import { MerchantsModule } from './merchants.module';
@Module({
imports: [MerchantsModule, GenerationModule],
controllers: [MerchantsController],
})
export class MerchantsHttpModule {}
@@ -0,0 +1,53 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { GenerationService } from '../generation/generation.service';
import { GenerationQueue } from '../generation/generation.queue';
import { MerchantsService, UpsertMerchantDto } from './merchants.service';
@Controller('v1/merchants')
export class MerchantsController {
constructor(
private readonly merchants: MerchantsService,
private readonly generation: GenerationService,
private readonly queue: GenerationQueue,
) {}
@Get()
list() {
return this.merchants.list();
}
@Get(':id')
get(@Param('id') id: string) {
return this.merchants.findWithTaxonomy(id);
}
/** o2o-site-AEO 사이트 발행 웹훅: 업체 등록 + 키워드 생성 예약 */
@Post('publish')
async publish(@Body() dto: UpsertMerchantDto & { generate?: boolean; sync?: boolean }) {
const merchant = await this.merchants.upsert(dto);
if (dto.generate === false) return { merchant, generation: 'skipped' };
if (dto.sync) {
const stats = await this.generation.runForMerchant(merchant.id, 'published');
return { merchant, generation: stats };
}
const jobId = await this.queue.enqueue(merchant.id, 'published');
return { merchant, generation: { queued: true, jobId } };
}
/** 수동 재생성 */
@Post(':id/generate')
async generate(
@Param('id') id: string,
@Query('sync') sync?: string,
@Query('count') count?: string,
) {
const target = count ? Math.min(Math.max(1, Number(count)), 500) : undefined;
if (sync === 'true' || sync === '1') {
return this.generation.runForMerchant(id, 'manual', target);
}
const m = await this.merchants.findWithTaxonomy(id);
const jobId = await this.queue.enqueue(m.id, 'manual');
return { queued: true, jobId };
}
}
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { MerchantsService } from './merchants.service';
@Module({
providers: [MerchantsService],
exports: [MerchantsService],
})
export class MerchantsModule {}
@@ -0,0 +1,92 @@
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { PG } from '../db/db.module';
import { asJson, Sql } from '../db/db';
export interface MerchantRow {
id: string;
external_id: string;
name: string;
industry_id: string | null;
region_id: string | null;
description: string;
profile: Record<string, unknown>;
site_url: string | null;
last_generated_at: Date | null;
}
export interface MerchantWithTaxonomy extends MerchantRow {
industry_name: string | null;
industry_path: string | null;
region_name: string | null;
region_path: string | null;
}
export interface UpsertMerchantDto {
externalId: string;
name: string;
industryId?: string | null;
regionId?: string | null;
description?: string;
profile?: Record<string, unknown>;
siteUrl?: string | null;
}
@Injectable()
export class MerchantsService {
constructor(@Inject(PG) private readonly sql: Sql) {}
/** o2o-site-AEO 가 사이트를 발행할 때 호출하는 진입점 */
async upsert(dto: UpsertMerchantDto): Promise<MerchantRow> {
const rows = await this.sql<MerchantRow[]>`
INSERT INTO merchant (external_id, name, industry_id, region_id, description, profile, site_url)
VALUES (${dto.externalId}, ${dto.name}, ${dto.industryId ?? null}, ${dto.regionId ?? null},
${dto.description ?? ''}, ${this.sql.json(asJson(dto.profile ?? {}))}, ${dto.siteUrl ?? null})
ON CONFLICT (external_id) DO UPDATE SET
name = EXCLUDED.name,
industry_id = EXCLUDED.industry_id,
region_id = EXCLUDED.region_id,
description = EXCLUDED.description,
profile = EXCLUDED.profile,
site_url = EXCLUDED.site_url,
updated_at = now()
RETURNING *`;
return rows[0];
}
async findWithTaxonomy(idOrExternalId: string): Promise<MerchantWithTaxonomy> {
const rows = await this.sql<MerchantWithTaxonomy[]>`
SELECT m.*,
i.name AS industry_name, i.path::text AS industry_path,
r.name AS region_name, r.path::text AS region_path
FROM merchant m
LEFT JOIN industry i ON i.id = m.industry_id
LEFT JOIN region r ON r.id = m.region_id
WHERE m.external_id = ${idOrExternalId}
OR (${isUuid(idOrExternalId)} AND m.id::text = ${idOrExternalId})
LIMIT 1`;
if (!rows[0]) throw new NotFoundException(`merchant not found: ${idOrExternalId}`);
return rows[0];
}
async list(limit = 50) {
return this.sql<MerchantRow[]>`
SELECT * FROM merchant ORDER BY created_at DESC LIMIT ${limit}`;
}
/** 주기 리프레시 대상: 한 번도 생성 안 됐거나 N일 지난 업체 */
async findStale(intervalDays: number, limit: number) {
return this.sql<Array<{ id: string; external_id: string }>>`
SELECT id, external_id FROM merchant
WHERE last_generated_at IS NULL
OR last_generated_at < now() - (${intervalDays} || ' days')::interval
ORDER BY last_generated_at NULLS FIRST
LIMIT ${limit}`;
}
async markGenerated(merchantId: string) {
await this.sql`UPDATE merchant SET last_generated_at = now() WHERE id = ${merchantId}`;
}
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const isUuid = (v: string) => UUID_RE.test(v);
+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;
}