Skip to content

Supabase RAG

Supabase를 기반으로 RAG 검색을 사용할 때는 pgvector 확장과 메타데이터 테이블 구조를 함께 운용합니다.

핵심 개념

  • documents: 원본 문서 단위 메타 데이터
  • document_chunks: chunk 단위 텍스트와 임베딩 결과
  • search_analytics: 질의 로그/평가용 기록(옵션)

필수 확장

sql
create extension if not exists vector;
create extension if not exists pgcrypto;

예시 스키마

sql
create table if not exists documents (
  id uuid primary key default gen_random_uuid(),
  title text not null,
  source_path text,
  mime_type text,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists document_chunks (
  id bigserial primary key,
  document_id uuid references documents(id) on delete cascade,
  chunk_index int not null,
  content text not null,
  metadata jsonb default '{}'::jsonb,
  embedding vector(1536),
  created_at timestamptz not null default now(),
  unique (document_id, chunk_index)
);

create index if not exists document_chunks_embedding_idx
  on document_chunks using ivfflat (embedding vector_cosine_ops)
  with (lists = 100);

샘플 검색 쿼리

sql
-- :query_embedding 은 vector(1536) 타입 바인딩 값
select
  d.title,
  c.chunk_index,
  c.content,
  1 - (c.embedding <=> :query_embedding) as similarity
from document_chunks c
join documents d on d.id = c.document_id
order by c.embedding <=> :query_embedding
limit 20;

운영 팁

  • 벡터 차원은 임베딩 모델에 맞춰 일치해야 함
  • ivfflat 인덱스는 데이터 규모가 커질수록 조회 성능 개선에 유리
  • 검색 품질은 similarity 임계값 조정과 재정렬 전략으로 최적화
  • 임베딩 업데이트가 잦으면 파티션/아카이빙 정책을 별도 계획