> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Search what was said in your videos with Supabase pgvector

> A tested Supabase recipe for Lovable, Bolt and other Supabase apps: split each video transcript into 30-second chunks, embed them with Supabase's built-in gte-small model, and let a user ask a question and jump to the moment in the video that answers it.

A "search my videos" or "chat with this video" feature needs two things: the transcript, with times, and a way to find the part that answers a question. On Supabase both fit in the project you already have. Importly returns the transcript with start times for every line, Supabase's built-in `gte-small` model turns each chunk into an embedding inside an Edge Function, and pgvector finds the closest chunks to a question. You don't need an OpenAI key or a separate vector database.

This recipe builds on [Save transcripts to Supabase from an Edge Function](/docs/integrations/supabase-edge-functions.md). Set that up first: it gives you the `transcripts` table, the `start-transcript` and `importly-webhook` functions, and the sweep for missed webhooks. Here you add:

* a `transcript_chunks` table with a pgvector column, and a `match_transcript_chunks` function;
* `index-transcripts`, which splits finished transcripts into chunks and embeds them a few at a time;
* `search-transcripts`, which takes a user's question and returns the matching moments from that user's own videos.

## 1. The table and the search function

Run this in the SQL editor or add it as a migration. Users can read only their own chunks, and `match_transcript_chunks` runs as the caller, so the same RLS policy limits every search to their own videos.

```sql theme={null}
create extension if not exists vector with schema extensions;

alter table public.transcripts add column chunked_at timestamptz;

create table public.transcript_chunks (
  id bigint generated always as identity primary key,
  transcript_id uuid not null references public.transcripts (id) on delete cascade,
  user_id uuid not null references auth.users (id) on delete cascade,
  start_seconds real not null,
  content text not null,
  embedding extensions.vector(384)
);

create index on public.transcript_chunks using hnsw (embedding extensions.vector_cosine_ops);
create index on public.transcript_chunks (id) where embedding is null;

alter table public.transcript_chunks enable row level security;

create policy "Users read their own chunks"
  on public.transcript_chunks for select to authenticated
  using ((select auth.uid()) = user_id);

-- Runs as the caller, so RLS limits it to their own videos
create function public.match_transcript_chunks(query_embedding extensions.vector(384), match_count int default 5)
returns table (transcript_id uuid, url text, start_seconds real, content text, similarity float)
language sql stable
security invoker
set search_path = ''
as $$
  select c.transcript_id, t.url, c.start_seconds, c.content,
    1 - (c.embedding operator(extensions.<=>) query_embedding) as similarity
  from public.transcript_chunks c
  join public.transcripts t on t.id = c.transcript_id
  where c.embedding is not null
  order by c.embedding operator(extensions.<=>) query_embedding
  limit least(match_count, 20);
$$;

revoke execute on function public.match_transcript_chunks from public, anon;
grant execute on function public.match_transcript_chunks to authenticated;
```

`gte-small` returns 384 numbers per text, which is why the column is `vector(384)`. A chunk's `embedding` stays `null` until `index-transcripts` gets to it, and searches skip those rows.

## 2. Chunk and embed

Put the shared code next to the `importly.ts` helper from the transcripts recipe. The transcript's `segments` are short lines with `start` and `end` in seconds; joining them into about 30 seconds of speech gives each chunk enough words to match a question and a start time to jump to.

```ts supabase/functions/_shared/chunks.ts theme={null}
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2'

// Supabase's built-in embedding model: 384 numbers per text, no extra API key
const model = new Supabase.ai.Session('gte-small')

export const embed = async (text: string) =>
  (await model.run(text, { mean_pool: true, normalize: true })) as number[]

type Segment = { start: number; end: number; text: string }

// About 30 seconds of speech per chunk, so a match points at a moment you can play
export const toChunks = (segments: Segment[], seconds = 30) => {
  const chunks: { start: number; text: string }[] = []
  for (const segment of segments) {
    const text = segment.text.trim()
    const last = chunks.at(-1)
    if (last && segment.start - last.start < seconds) last.text += ` ${text}`
    else chunks.push({ start: segment.start, text })
  }
  return chunks
}

// Split each finished transcript into chunks once. Embedding happens later, a few at a time.
export const chunkNewTranscripts = async (supabase: SupabaseClient) => {
  const { data: claimed } = await supabase
    .from('transcripts')
    .update({ chunked_at: new Date().toISOString() })
    .eq('status', 'completed')
    .is('chunked_at', null)
    .select('id, user_id, segments')

  for (const row of claimed ?? []) {
    const rows = toChunks(row.segments ?? []).map((chunk) => ({
      transcript_id: row.id,
      user_id: row.user_id,
      start_seconds: chunk.start,
      content: chunk.text,
    }))
    if (rows.length) await supabase.from('transcript_chunks').insert(rows)
  }
  return claimed?.length ?? 0
}

// Each embedding takes real CPU time, and an Edge Function that uses too much
// fails with 546 WORKER_RESOURCE_LIMIT, so embed a small batch per call
export const embedPendingChunks = async (supabase: SupabaseClient, batch = 5) => {
  const { data: pending } = await supabase
    .from('transcript_chunks')
    .select('id, content')
    .is('embedding', null)
    .order('id')
    .limit(batch)

  for (const chunk of pending ?? []) {
    const embedding = await embed(chunk.content)
    await supabase.from('transcript_chunks').update({ embedding: JSON.stringify(embedding) }).eq('id', chunk.id)
  }
  return pending?.length ?? 0
}
```

The batch is small on purpose. One embedding takes about 160 ms of CPU, and when we embedded a whole 18-minute transcript (35 chunks) in one call, the function failed with `546 WORKER_RESOURCE_LIMIT` before the tenth. Five per call stays well inside the limit.

## 3. The indexing function

Each call chunks any newly finished transcripts, embeds one batch, and calls itself again while there is more to do. Claiming a transcript with `chunked_at` first means two calls at once never chunk the same video twice.

```ts supabase/functions/index-transcripts/index.ts theme={null}
import { createClient } from 'npm:@supabase/supabase-js@2'
import { chunkNewTranscripts, embedPendingChunks } from '../_shared/chunks.ts'

const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!)
const BATCH = 5
const SELF = `${Deno.env.get('SUPABASE_URL')}/functions/v1/index-transcripts`

Deno.serve(async (req) => {
  const transcripts = await chunkNewTranscripts(supabase)
  const embedded = await embedPendingChunks(supabase, BATCH)

  // A full batch means more may be waiting: call this function again for the next one
  if (embedded === BATCH) {
    EdgeRuntime.waitUntil(
      fetch(SELF, { method: 'POST', headers: { Authorization: req.headers.get('Authorization') ?? '' } }),
    )
  }
  return Response.json({ transcripts, embedded })
})
```

In our test this embedded all 35 chunks of an 18-minute video about 15 seconds after the first call, in seven calls.

Start it as soon as a transcript is saved: in `importly-webhook` from the transcripts recipe, add one call after `saveJob`:

```ts supabase/functions/importly-webhook/index.ts theme={null}
  if (data?.type === 'transcribe' && typeof data.jobId === 'string') {
    await saveJob(supabase, data.jobId)
    // index the new transcript now instead of waiting for the next cron run
    EdgeRuntime.waitUntil(
      fetch(`${Deno.env.get('SUPABASE_URL')}/functions/v1/index-transcripts`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${Deno.env.get('SUPABASE_ANON_KEY')}` },
      }),
    )
  }
```

Also schedule `index-transcripts` every few minutes with [Supabase Cron](https://supabase.com/docs/guides/functions/schedule-functions), next to `sweep-transcripts`. That picks up transcripts the sweep saved and any batch whose call failed.

## 4. The search function

The frontend calls this with the user's session. The function embeds the question with the same model and asks Postgres for the five closest chunks the user is allowed to see.

```ts supabase/functions/search-transcripts/index.ts theme={null}
import { createClient } from 'npm:@supabase/supabase-js@2'
import { embed } from '../_shared/chunks.ts'

const cors = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: cors })

  // Use the caller's own session, so RLS returns only their videos
  const supabase = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_ANON_KEY')!, {
    global: { headers: { Authorization: req.headers.get('Authorization') ?? '' } },
  })
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return Response.json({ error: 'Sign in first' }, { status: 401, headers: cors })

  const { query } = await req.json()
  if (typeof query !== 'string' || !query.trim()) {
    return Response.json({ error: 'Send a query' }, { status: 400, headers: cors })
  }

  const { data, error } = await supabase.rpc('match_transcript_chunks', {
    query_embedding: JSON.stringify(await embed(query)),
    match_count: 5,
  })
  if (error) return Response.json({ error: error.message }, { status: 500, headers: cors })

  return Response.json(data, { headers: cors })
})
```

Deploy both:

```bash theme={null}
supabase functions deploy index-transcripts
supabase functions deploy search-transcripts
```

## 5. Call it from your app

```ts theme={null}
const { data: matches, error } = await supabase.functions.invoke('search-transcripts', {
  body: { query: 'how does the network learn its weights' },
})

// Each match: transcript_id, url, start_seconds, content, similarity.
// For a YouTube link, open the video at that moment:
const linkAt = (url: string, seconds: number) => {
  const link = new URL(url)
  link.searchParams.set('t', `${Math.floor(seconds)}s`)
  return link.toString()
}
```

For other sites, or a file you saved to [Supabase Storage](/docs/integrations/supabase-storage.md), seek your own player to `start_seconds`.

We ran this against a real 18-minute lecture (3Blue1Brown's "But what is a neural network?"). The question "how does the network learn its weights" returned five moments between 9:08 and 15:31, the part of the video that explains weights and biases. A second signed-in user got an empty list for the same question, and a call without a session got `401`.

## Things to know

Only finished transcripts are indexed. A transcript that failed (a private or removed video) keeps `status: 'failed'` and never gets chunks.

Long videos take more calls. A two-hour video is about 240 chunks, so about 48 calls, and each Edge Function call counts toward your Supabase plan's invocations.

`gte-small` is trained on English text. For videos in other languages, use a multilingual embedding model and change `vector(384)` to its size.

To answer in sentences rather than return the moments ("chat with this video"), send the top matches and the question to the model your app already uses, and show each `start_seconds` as a citation.

> [!NOTE]
>
> A transcript from captions costs $0.003. Speech-to-text for a video without captions is $0.01 per minute, and `maxCostDollars` stops a long one before it's charged. The embeddings run inside your Supabase project, so Importly doesn't charge for them. Try it free, no card required. See [Pricing & credits](/docs/billing.md).

## Let your agent write it

Using Lovable's chat, Bolt, Claude Code or Cursor on this project? Connect the [MCP server](/docs/integrations/mcp.md) and ask it to add transcript search with Importly and pgvector: it reads the same integration guide and can test with a real link first. See [Build with your agent](/docs/integrations/build-with-your-agent.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.