-- ===================================================================== -- k12-math-rag-tutor : 006_ebsi_embedding.sql -- 뜻(의미) 검색을 위한 벡터 열과, 글자 검색 + 뜻 검색을 섞은 검색 함수. -- 임베딩 모델: BAAI/bge-m3 (1024차원, 사용자 선택 2026-12-01) -- Supabase SQL Editor 에서 통째로 실행합니다. (여러 번 실행해도 안전) -- 순서: 005_ebsi_search.sql 을 먼저 실행한 뒤 이 파일 -- -- 이 파일이 하는 일 -- 1) pgvector 확장 (벡터 저장·거리 계산) -- 2) questions 에 embedding(1024차원) 열과 embedding_model(어떤 모델로 만들었는지) 열 추가 -- 3) 벡터 근접 검색 인덱스(HNSW, 코사인 거리) -- 4) 혼합 검색 함수 search_items() — 뜻 0.7 + 글자 0.3. 서버(service_role)만 호출 가능 -- -- 주의 -- * 차원 1024 는 bge-m3 전용. 모델을 바꾸면 열을 지우고 다시 만들어야 함(다른 모델 벡터끼리는 비교 불가). -- * 검색어도 반드시 같은 모델(bge-m3)로 벡터를 만들어 q_embedding 으로 넘겨야 함. -- * 임베딩 값은 적재 스크립트가 채움(사용자가 직접 실행). 이 파일은 빈 열만 만듦. -- ===================================================================== -- 1. 확장 create extension if not exists vector with schema extensions; -- 2. 열 alter table questions add column if not exists embedding extensions.vector(1024), add column if not exists embedding_model text; -- 예: 'BAAI/bge-m3' -- 3. 인덱스 (코사인 거리) create index if not exists questions_embedding_idx on questions using hnsw (embedding extensions.vector_cosine_ops); -- 4. 혼합 검색 함수 -- 점수 = 0.7 x 뜻 유사도(1 - 코사인 거리) + 0.3 x 글자 유사도(005 와 같은 계산) -- 임베딩이 아직 없는 문항은 글자 유사도만으로 점수를 매김. -- p_student=true(기본)이면 게시(published)·이용허락(cleared) 문항만 -> EBSi 초안은 학생에게 안 나옴. create or replace function search_items( q_embedding extensions.vector(1024), q_text text, p_grade text default null, p_year smallint default null, p_unit text default null, p_diff difficulty default null, p_limit int default 5, p_student boolean default true ) returns table (id uuid, score real) language sql stable set search_path = public, extensions as $$ select q.id, (case when q.embedding is null or q_embedding is null then greatest(similarity(coalesce(q.search_text, ''), coalesce(q_text, '')), word_similarity(coalesce(q_text, ''), coalesce(q.search_text, ''))) else 0.7 * (1 - (q.embedding <=> q_embedding)) + 0.3 * greatest(similarity(coalesce(q.search_text, ''), coalesce(q_text, '')), word_similarity(coalesce(q_text, ''), coalesce(q.search_text, ''))) end)::real as score from questions q where (q.embedding is not null or q.search_text is not null) and (not p_student or (q.status = 'published' and q.rights_status = 'cleared')) and (p_grade is null or q.grade_code = p_grade) and (p_year is null or q.exam_year = p_year) and (p_unit is null or q.unit_id = p_unit) and (p_diff is null or q.difficulty = p_diff) order by score desc limit greatest(1, least(p_limit, 50)); $$; revoke all on function search_items(extensions.vector, text, text, smallint, text, difficulty, int, boolean) from public; revoke all on function search_items(extensions.vector, text, text, smallint, text, difficulty, int, boolean) from anon, authenticated; grant execute on function search_items(extensions.vector, text, text, smallint, text, difficulty, int, boolean) to service_role; -- 확인용 -- select count(*) filter (where embedding is not null) as 벡터있음, count(*) as 전체 from questions where source = 'ebsi';