발행이 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>
125 lines
4.1 KiB
TypeScript
125 lines
4.1 KiB
TypeScript
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}`;
|
|
}
|
|
}
|