mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
feat: Improve kb search to be on pair with docs search v2 (#53454)
## Problem though they use the same package and were conceived to be 1-1, search v2 in Docs and Kb search have some differences: - Docs new search function is more complex to prevent no results, improvements kb search hasn't seen. For example, when you look for "passwor", incomplete term, Docs return results around the password term, but kb doesn't **(see screenshot below)**. - On kb side, we have a `content=true` parameter to fetch markdown content from results to serve some agentic tools, but Docs search never received that upgrade. Fair to say, in docs we are not covering all routes in markdown at the moment so it's not 100% reliable, but whenever we reach that, we can switch to use this search endpoint for MCP tooling. <img width="1512" height="867" alt="Screenshot 2026-11-16 at 13 06 08" src="https://github.com/user-attachments/assets/99baa772-d4b1-4d73-bfa7-7110d5635f0a" /> ## Solution - Add a migration file on kb search table to match docs search SQL function. - Add `content=true` parameter to docs search <!-- ## Preview links If relevant, include links to changed pages for easy review access. Copy the preview base URL from the Vercel bot comment on this PR. Use the following table as an example template. | Site | Live | Preview | Search for | | -------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------- | | WWW | [/blog/your-post](https://supabase.com/blog/your-post) | [/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post) | unique phrase from the change | | Docs | [/docs/guides/your-page](https://supabase.com/docs/guides/your-page) | [/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page) | unique phrase from the change | | Studio | [/dashboard](https://supabase.com/dashboard) | [/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard) | unique phrase from the change | | Design system | [/design-system](https://supabase.com/design-system) | [/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system) | unique phrase from the change | | UI library | [/library](https://supabase.com/library) | [/library](https://ui-library-git-branch-name-supabase.vercel.app/library) | unique phrase from the change | | Knowledge base | [/kb/guides/your-page](https://supabase.com/kb/guides/your-page) | [/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page) | unique phrase from the change | --> <!-- ## Additional context Optionally add any other context or screenshots. --> ## Review instructions - To test kb new search function, you would have checkout this branch, to spin locally kb search migration and search, other way we need to wait for merging and testing. It's important Supabase integration returns _green_ here to make sure migrations run safely. - For docs search new parameter. Open the preview for docs in this branch: 1. Open the search modal, and open your browser's dev tools, go to the network tab 1. Do a search, grab the URL and open it in a new tab 1. Add `content=true` and `limit=3` as query prameters 1. You should get back three results with a content property containing the markdown content of each route (see example below) <img width="1273" height="793" alt="Screenshot 2026-11-16 at 13 12 32" src="https://github.com/user-attachments/assets/d1af4663-e17e-438e-99ac-4e63f51460a9" /> ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
This commit is contained in:
1 parent
dde52ce6e8
commit
f920456c3f
4 files changed
+259
-1
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { BASE_PATH, IS_DEV, IS_PRODUCTION, PROD_URL } from '~/lib/constants'
|
||||
|
||||
/**
|
||||
* Resolves the docs base URL (origin + base path) from trusted sources only, so the Host header
|
||||
* can't redirect the fetches made for `content=true` (SSRF). The request origin is used in local
|
||||
* development only.
|
||||
*/
|
||||
export function resolveDocsBaseUrl(requestUrl: string): string | undefined {
|
||||
if (IS_PRODUCTION) return PROD_URL
|
||||
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}${BASE_PATH}`
|
||||
if (process.env.NEXT_PUBLIC_SITE_URL) return `${process.env.NEXT_PUBLIC_SITE_URL}${BASE_PATH}`
|
||||
if (IS_DEV) return `${new URL(requestUrl).origin}${BASE_PATH}`
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the markdown export of a page (`<base>/<slug>.md`). Returns null when it can't be
|
||||
* loaded, including pages with no markdown export (only guides have one).
|
||||
*/
|
||||
export async function fetchMarkdown(
|
||||
baseUrl: string | undefined,
|
||||
slug: string
|
||||
): Promise<string | null> {
|
||||
const segments = slug.split('/')
|
||||
if (!baseUrl || segments[0] !== 'guides' || segments.some((s) => !s || s === '.' || s === '..')) {
|
||||
return null
|
||||
}
|
||||
|
||||
const url = `${baseUrl}/${segments.map(encodeURIComponent).join('/')}.md`
|
||||
try {
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) {
|
||||
console.warn(`Failed to fetch docs content from ${url}: ${response.status}`)
|
||||
return null
|
||||
}
|
||||
return await response.text()
|
||||
} catch (error) {
|
||||
console.warn(`Failed to fetch docs content from ${url}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const rpc = vi.fn()
|
||||
vi.mock('~/scripts/search_v2/supabase', () => ({
|
||||
SEARCH_FUNCTION: 'docs_search_v2',
|
||||
createSupabaseClient: () => ({ rpc }),
|
||||
}))
|
||||
vi.mock('@sentry/nextjs', () => ({ captureException: vi.fn() }))
|
||||
vi.mock('~/lib/constants', () => ({
|
||||
BASE_PATH: '/docs',
|
||||
IS_DEV: false,
|
||||
IS_PRODUCTION: true,
|
||||
PROD_URL: 'https://supabase.com/docs',
|
||||
}))
|
||||
|
||||
const { GET } = await import('./route')
|
||||
|
||||
const guideRow = { slug: 'guides/auth/users', page_title: 'Users', heading: 'Users', score: 3500 }
|
||||
const referenceRow = { slug: 'reference/javascript/auth-signup', page_title: 'signUp', score: 3400 }
|
||||
|
||||
const search = (params: string) =>
|
||||
GET(new Request(`https://supabase.com/docs/api/search_v2?${params}`) as never)
|
||||
|
||||
describe('GET /api/search_v2', () => {
|
||||
beforeEach(() => {
|
||||
rpc.mockReset()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('rejects a missing query', async () => {
|
||||
expect((await search('')).status).toBe(400)
|
||||
expect(rpc).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns the rows as is, without fetching content, by default', async () => {
|
||||
rpc.mockResolvedValue({ data: [guideRow], error: null })
|
||||
const fetch = vi.fn()
|
||||
vi.stubGlobal('fetch', fetch)
|
||||
|
||||
const response = await search('q=users&limit=3')
|
||||
|
||||
expect(rpc).toHaveBeenCalledWith('docs_search_v2', { query_text: 'users', match_limit: 3 })
|
||||
expect(await response.json()).toEqual([guideRow])
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('adds the markdown of guides when content=true', async () => {
|
||||
rpc.mockResolvedValue({ data: [guideRow], error: null })
|
||||
const fetch = vi.fn(async () => new Response('# Users'))
|
||||
vi.stubGlobal('fetch', fetch)
|
||||
|
||||
const results = await (await search('q=users&content=true')).json()
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('https://supabase.com/docs/guides/auth/users.md')
|
||||
expect(results).toEqual([{ ...guideRow, content: '# Users' }])
|
||||
})
|
||||
|
||||
it('sets content to null for pages with no markdown or that fail to load', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const missing = { ...guideRow, slug: 'guides/missing' }
|
||||
rpc.mockResolvedValue({ data: [referenceRow, missing], error: null })
|
||||
const fetch = vi.fn(async () => new Response('', { status: 404 }))
|
||||
vi.stubGlobal('fetch', fetch)
|
||||
|
||||
const results = await (await search('q=x&content=true')).json()
|
||||
|
||||
// reference pages have no markdown export, so they are not fetched at all
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
expect(results.map((r: { content: string | null }) => r.content)).toEqual([null, null])
|
||||
})
|
||||
|
||||
it('returns 500 when the query fails', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
rpc.mockResolvedValue({ data: null, error: { message: 'boom' } })
|
||||
expect((await search('q=x')).status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,7 @@ import * as Sentry from '@sentry/nextjs'
|
||||
import { createSupabaseClient, SEARCH_FUNCTION } from '~/scripts/search_v2/supabase'
|
||||
import { type NextRequest } from 'next/server'
|
||||
|
||||
import { fetchMarkdown, resolveDocsBaseUrl } from './content'
|
||||
import { corsHeaders } from './cors'
|
||||
|
||||
export const runtime = 'edge'
|
||||
@@ -15,6 +16,7 @@ export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const query = searchParams.get('q')?.trim()
|
||||
const limit = Number(searchParams.get('limit')) || 10
|
||||
const includeContent = searchParams.get('content') === 'true'
|
||||
|
||||
if (!query) {
|
||||
return Response.json({ error: 'Missing q parameter' }, { status: 400, headers: corsHeaders })
|
||||
@@ -34,7 +36,19 @@ export async function GET(request: NextRequest) {
|
||||
return Response.json({ error: error.message }, { status: 500, headers: corsHeaders })
|
||||
}
|
||||
|
||||
return Response.json(data, { headers: corsHeaders })
|
||||
if (!includeContent) {
|
||||
return Response.json(data, { headers: corsHeaders })
|
||||
}
|
||||
|
||||
// Attach each page's markdown export; null when it has none or can't be loaded.
|
||||
const baseUrl = resolveDocsBaseUrl(request.url)
|
||||
const results = await Promise.all(
|
||||
(data as { slug: string }[]).map(async (row) => ({
|
||||
...row,
|
||||
content: await fetchMarkdown(baseUrl, row.slug),
|
||||
}))
|
||||
)
|
||||
return Response.json(results, { headers: corsHeaders })
|
||||
} catch (error) {
|
||||
console.error('Error handling docs search v2 request:', error)
|
||||
Sentry.captureException(error, { tags: { route: 'search_v2' } })
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
-- Align search_kb with docs_search_v2: same tiered matching algorithm, applied to public.kb_search.
|
||||
-- Same name, arguments and return columns as before, so the API route and client are unchanged.
|
||||
-- Execution rights are unchanged too: only service_role can call it.
|
||||
--
|
||||
-- Differences from the previous search_kb:
|
||||
-- * No IDF-weighted scoring and no minimum-score cutoff.
|
||||
-- * Falls back to OR matching and then to typo-tolerant trigram matching when the stricter
|
||||
-- tiers return nothing.
|
||||
-- * Partial words ("edg", "edge fun") match as prefixes.
|
||||
|
||||
create extension if not exists pg_trgm with schema extensions;
|
||||
|
||||
create index if not exists kb_search_page_title_trgm_idx
|
||||
on public.kb_search using gin (page_title extensions.gin_trgm_ops);
|
||||
create index if not exists kb_search_heading_trgm_idx
|
||||
on public.kb_search using gin (heading extensions.gin_trgm_ops);
|
||||
|
||||
-- Matches are tiered, and score bands keep a better tier above every match of a lower tier:
|
||||
-- strict (3000-3999) every term is a whole word (websearch_to_tsquery)
|
||||
-- prefix (2000-2999) every term is the start of a word ("edge fun" => "edge functions")
|
||||
-- or (1000-1999) any term matches, only when strict and prefix return nothing
|
||||
-- trigram (0-899) typo-tolerant match on page title or heading, only when all of the above
|
||||
-- return nothing
|
||||
-- Within a tier the score is ts_rank_cd normalised to 0..1 (normalization flag 32 => rank / (rank + 1)).
|
||||
--
|
||||
-- search_path is empty (as in the previous search_kb), so everything outside pg_catalog is
|
||||
-- schema-qualified, including the pg_trgm functions and operators.
|
||||
create or replace function public.search_kb(query_text text, match_limit int default 10)
|
||||
returns table (
|
||||
slug text,
|
||||
page_title text,
|
||||
heading text,
|
||||
heading_level smallint,
|
||||
heading_path text[],
|
||||
excerpt text,
|
||||
score int
|
||||
)
|
||||
language sql
|
||||
stable
|
||||
set search_path = ''
|
||||
-- Minimum similarity for the trigram tier (pg_trgm default is 0.6).
|
||||
set pg_trgm.word_similarity_threshold = '0.4'
|
||||
as $$
|
||||
with words as (
|
||||
-- Lowercase alphanumeric words only, so the terms are safe to put in a tsquery.
|
||||
select w
|
||||
from regexp_split_to_table(
|
||||
lower(regexp_replace(coalesce(query_text, ''), '[^[:alnum:]]+', ' ', 'g')),
|
||||
'\s+'
|
||||
) as w
|
||||
where w <> ''
|
||||
),
|
||||
q as (
|
||||
select
|
||||
websearch_to_tsquery('english', query_text) as strict_q,
|
||||
-- English stop words ("how", "to", "the") are dropped when the query is parsed.
|
||||
to_tsquery('english', (select string_agg(w || ':*', ' & ') from words)) as prefix_q,
|
||||
to_tsquery('english', (select string_agg(w || ':*', ' | ') from words)) as or_q
|
||||
),
|
||||
strict_hits as (
|
||||
select
|
||||
d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
|
||||
3000 + round(ts_rank_cd(d.fts, q.strict_q, 32) * 999)::int as score
|
||||
from public.kb_search d, q
|
||||
where d.fts @@ q.strict_q
|
||||
),
|
||||
prefix_hits as (
|
||||
select
|
||||
d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
|
||||
2000 + round(ts_rank_cd(d.fts, q.prefix_q, 32) * 999)::int as score
|
||||
from public.kb_search d, q
|
||||
where d.fts @@ q.prefix_q
|
||||
),
|
||||
primary_hits as (
|
||||
select * from strict_hits
|
||||
union all
|
||||
select * from prefix_hits
|
||||
),
|
||||
or_hits as (
|
||||
select
|
||||
d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
|
||||
1000 + round(ts_rank_cd(d.fts, q.or_q, 32) * 999)::int as score
|
||||
from public.kb_search d, q
|
||||
where d.fts @@ q.or_q
|
||||
and not exists (select 1 from primary_hits)
|
||||
),
|
||||
trigram_hits as (
|
||||
select
|
||||
d.slug, d.page_title, d.heading, d.heading_level, d.heading_path, d.excerpt,
|
||||
round(
|
||||
greatest(
|
||||
extensions.word_similarity(query_text, d.page_title),
|
||||
extensions.word_similarity(query_text, d.heading)
|
||||
) * 899
|
||||
)::int as score
|
||||
from public.kb_search d
|
||||
where (
|
||||
query_text operator(extensions.<%) d.page_title
|
||||
or query_text operator(extensions.<%) d.heading
|
||||
)
|
||||
and not exists (select 1 from primary_hits)
|
||||
and not exists (select 1 from or_hits)
|
||||
),
|
||||
ranked as (
|
||||
select * from primary_hits
|
||||
union all
|
||||
select * from or_hits
|
||||
union all
|
||||
select * from trigram_hits
|
||||
),
|
||||
-- A page can have several matching sections; keep only its best-scoring one so the
|
||||
-- same route doesn't take up multiple slots in the results.
|
||||
best_per_page as (
|
||||
select distinct on (r.slug) r.*
|
||||
from ranked r
|
||||
order by r.slug, r.score desc, r.heading_level asc
|
||||
)
|
||||
select b.slug, b.page_title, b.heading, b.heading_level, b.heading_path, b.excerpt, b.score
|
||||
from best_per_page b
|
||||
order by b.score desc, b.heading_level asc, b.slug asc
|
||||
limit greatest(1, least(coalesce(match_limit, 10), 100));
|
||||
$$;
|
||||
|
||||
-- Re-asserted so the grants stay correct even if the function is ever recreated.
|
||||
revoke execute on function public.search_kb(text, int) from public, anon, authenticated;
|
||||
grant execute on function public.search_kb(text, int) to service_role;
|
||||
Reference in new issue
Block a user