Skip to content

Instantly share code, notes, and snippets.

@ahmadrosid
Last active July 14, 2023 16:02
Show Gist options
  • Select an option

  • Save ahmadrosid/18202fff9c0ca8c0825d7f5af5c17c05 to your computer and use it in GitHub Desktop.

Select an option

Save ahmadrosid/18202fff9c0ca8c0825d7f5af5c17c05 to your computer and use it in GitHub Desktop.

Setup supabase pgvector:

More information on Supabase vector column here

Enable pgvector extensions:

  1. Go to the Database page in the Dashboard.
  2. Click on Extensions in the sidebar.
  3. Search for "vector" and enable the extension.

Create table documents:

create table documents (
  id serial primary key,
  title text not null
);

Create table chunks:

create table chunks (
  id serial primary key,
  document_id serial not null,
  body text not null,
  embedding vector(1536),
  foreign key (document_id) references documents (id)
);

Create rpc function:

create or replace function match_documents (
  query_embedding vector(1536),
  match_threshold float,
  match_count int,
  document_ids int[]
)
returns table (
  id bigint,
  body text,
  document_id int,
  similarity float
)
language sql stable
as $$
  select
    chunks.id,
    chunks.body,
    chunks.document_id,
    1 - (chunks.embedding <=> query_embedding) as similarity
  from chunks
  where 
    1 - (chunks.embedding <=> query_embedding) > match_threshold
    AND chunks.document_id = any(document_ids)
  order by similarity desc
  limit match_count;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment