AI & tools

Vectors & AI

pgvector embeddings, semantic search and RAG.

This page is available in Polish only for now. The commands, code and API calls below are the same in every language — an English translation is on its way. Open the Polish page

Rozszerzenie pgvector jest dostępne w każdym projekcie. Przechowujesz embeddingi obok danych biznesowych i wyszukujesz je jednym zapytaniem SQL — bez osobnej bazy wektorowej.

Tabela z embeddingami

create extension if not exists vector;

create table documents (
  id bigint generated always as identity primary key,
  content text not null,
  metadata jsonb default '{}',
  embedding vector(1536)
);

create index on documents using hnsw (embedding vector_cosine_ops);

Funkcja wyszukiwania

create or replace function match_documents(
  query_embedding vector(1536),
  match_count int default 5,
  min_similarity float default 0.75
)
returns table (id bigint, content text, similarity float)
language sql stable as $$
  select id, content, 1 - (embedding <=> query_embedding) as similarity
  from documents
  where 1 - (embedding <=> query_embedding) > min_similarity
  order by embedding <=> query_embedding
  limit match_count;
$$;

Zapis i wyszukiwanie z aplikacji

const embedding = await embed(tekst); // dowolny model embeddingów, np. 1536 wymiarów

await supabase.from("documents").insert({ content: tekst, embedding });

const { data: matches } = await supabase.rpc("match_documents", {
  query_embedding: await embed(pytanie),
  match_count: 5,
});

RAG w skrócie

  1. Podziel dokumenty na fragmenty (300–800 tokenów).
  2. Policz embeddingi i zapisz je w tabeli.
  3. Dla pytania użytkownika znajdź najbliższe fragmenty przez match_documents.
  4. Przekaż znalezione fragmenty jako kontekst do modelu językowego (np. Claude).

Indeks HNSW zapewnia szybkie wyszukiwanie przy milionach wektorów; dla mniejszych zbiorów wystarczy skan sekwencyjny.