[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:
1 parent
bdc69a80f2
commit
01098835e9
70 files changed
+105484
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user