Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

refactor(search): rank by ts_rank in a static global_search

fzaninotto83e80ce39284
diff --git a/src/components/atomic-crm/providers/fakerest/search.ts b/src/components/atomic-crm/providers/fakerest/search.ts
index df7df6c2..b181342c 100644
--- a/src/components/atomic-crm/providers/fakerest/search.ts
+++ b/src/components/atomic-crm/providers/fakerest/search.ts
@@ -58,8 +58,10 @@ const byNameMatchThenDateDesc = (a: RankedResult, b: RankedResult) =>
*
* It follows the same rules: the same fields per resource, every query word
* must start a word of the record (accents and case ignored), open tasks and
- * live deals only, records whose name matches first, then newest first, each
- * resource's first `maxResults` matches.
+ * live deals only, newest first, each resource's first `maxResults` matches.
+ * Postgres ranks companies, contacts and deals by relevance with `ts_rank`,
+ * where the name weighs most: this approximates it by listing the records whose
+ * name matches first.
* It scans every record, which is fine for the in-browser demo data.
*/
export async function getSearchResults(
diff --git a/supabase/migrations/20261029133628_global_search_rank_name_matches.sql b/supabase/migrations/20261029133628_global_search_rank_name_matches.sql
index ff8a24f1..af777515 100644
--- a/supabase/migrations/20261029133628_global_search_rank_name_matches.sql
+++ b/supabase/migrations/20261029133628_global_search_rank_name_matches.sql
@@ -1,5 +1,5 @@
-- Weight the name A in the fts documents of companies, contacts and deals, so
--- global_search() can rank name matches first without slowing common words.
+-- global_search() can rank them by relevance and list name matches first.
-- db diff turns a generated column change into an invalid "set default": the
-- fts columns are dropped and rebuilt instead, with their indexes and
-- statistics target.
@@ -39,118 +39,84 @@ alter table public.contacts alter column fts set statistics 10000;
set check_function_bodies = off;
-CREATE OR REPLACE FUNCTION public.search_name_query(query text)
- RETURNS tsquery
- LANGUAGE sql
- IMMUTABLE PARALLEL SAFE STRICT
- SET search_path TO ''
-AS $function$ select replace(public.search_query(query)::text, ':*', ':*A')::tsquery $function$
-;
-
CREATE OR REPLACE FUNCTION public.global_search(query text, resources text[] DEFAULT NULL::text[], max_results integer DEFAULT 50)
RETURNS TABLE(resource text, record_id bigint, title text, subtitle text, contact_id bigint, deal_id bigint, date timestamp with time zone, content text)
LANGUAGE plpgsql
STABLE
SET search_path TO ''
+ SET plan_cache_mode TO 'force_custom_plan'
AS $function$
+#variable_conflict use_column
declare
tsq tsquery := public.search_query(query);
- name_tsq tsquery := public.search_name_query(query);
- -- Placeholders: %1$L is the query, %2$s the row limit. Branches of named
- -- resources also take %3$s, whether the name matches, and %4$s, the
- -- matching condition on fts.
- branch_templates constant jsonb := jsonb_build_object(
- 'companies', $q$
- select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at,
- concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr),
- %3$s as is_name_match
- from public.companies c
- where %4$s
- order by c.created_at desc
- limit %2$s $q$,
- 'contacts', $q$
- select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
- (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
- concat_ws(' · ', co.title, co.background,
- (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
- (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)),
- %3$s as is_name_match
- from public.contacts co
- where %4$s
- order by co.first_seen desc nulls last
- limit %2$s $q$,
- 'deals', $q$
- select 'deals', d.id, d.name,
- (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
- concat_ws(' · ', variadic d.categories || d.description),
- %3$s as is_name_match
- from public.deals d
- where d.archived_at is null and %4$s
- order by d.created_at desc
- limit %2$s $q$,
- 'tasks', $q$
- select 'tasks', t.id, left(t.text, 200),
- (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
- t.contact_id, null::bigint, t.created_at,
- concat_ws(' · ', t.text, t.type), false as is_name_match
- from public.tasks t
- where t.done_date is null and t.fts @@ %1$L::tsquery
- order by t.created_at desc
- limit %2$s $q$,
- 'contact_notes', $q$
- select 'contact_notes', cn.id, left(cn.text, 200),
- (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
- cn.contact_id, null::bigint, cn.date,
- concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)), false as is_name_match
- from public.contact_notes cn
- where cn.fts @@ %1$L::tsquery
- order by cn.date desc nulls last
- limit %2$s $q$,
- 'deal_notes', $q$
- select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
- concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)), false as is_name_match
- from public.deal_notes dn
- join public.deals nd on nd.id = dn.deal_id
- where nd.archived_at is null and dn.fts @@ %1$L::tsquery
- order by dn.date desc nulls last
- limit %2$s $q$
- );
- -- A named resource's branch runs once with each condition
- named_resources constant text[] := array['companies', 'contacts', 'deals'];
- name_match constant text := format('fts @@ %L::tsquery', name_tsq);
- other_match constant text := format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq, name_tsq);
row_limit constant integer := least(coalesce(max_results, 50), 200);
- columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_name_match';
- branches text[];
begin
if tsq is null or row_limit < 1 then
return;
end if;
- select array_agg(case
- when b.name = any(named_resources) then format(
- '(select * from ((%s) union all (%s)) halves(%s) order by is_name_match desc, date desc nulls last limit %s)',
- format(template, tsq, row_limit, 'true', name_match),
- format(template, tsq, row_limit, 'false', other_match),
- columns,
- row_limit)
- else format('(%s)', format(template, tsq, row_limit))
- end)
- into branches
- from jsonb_each_text(branch_templates) as b(name, template)
- where resources is null or b.name = any(resources);
-
- if branches is null then
- return;
- end if;
-
- return query execute format(
- 'select resource, record_id, title, subtitle, contact_id, deal_id, date, content
- from (%s) results(%s)
- order by is_name_match desc, date desc nulls last',
- array_to_string(branches, ' union all '),
- columns
- );
+ return query
+ select resource, record_id, title, subtitle, contact_id, deal_id, date, content
+ from (
+ (select 'companies' as resource, c.id as record_id, c.name as title, c.sector as subtitle,
+ null::bigint as contact_id, null::bigint as deal_id, c.created_at as date,
+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr) as content,
+ ts_rank(c.fts, tsq) as rank
+ from public.companies c
+ where (resources is null or 'companies' = any(resources)) and c.fts @@ tsq
+ order by rank desc, c.created_at desc
+ limit row_limit)
+ union all
+ (select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
+ (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
+ concat_ws(' · ', co.title, co.background,
+ (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)),
+ ts_rank(co.fts, tsq) as rank
+ from public.contacts co
+ where (resources is null or 'contacts' = any(resources)) and co.fts @@ tsq
+ order by rank desc, co.first_seen desc nulls last
+ limit row_limit)
+ union all
+ (select 'deals', d.id, d.name,
+ (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
+ concat_ws(' · ', variadic d.categories || d.description),
+ ts_rank(d.fts, tsq) as rank
+ from public.deals d
+ where (resources is null or 'deals' = any(resources)) and d.archived_at is null and d.fts @@ tsq
+ order by rank desc, d.created_at desc
+ limit row_limit)
+ union all
+ (select 'tasks', t.id, left(t.text, 200),
+ (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
+ t.contact_id, null::bigint, t.created_at,
+ concat_ws(' · ', t.text, t.type),
+ 0
+ from public.tasks t
+ where (resources is null or 'tasks' = any(resources)) and t.done_date is null and t.fts @@ tsq
+ order by t.created_at desc
+ limit row_limit)
+ union all
+ (select 'contact_notes', cn.id, left(cn.text, 200),
+ (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
+ cn.contact_id, null::bigint, cn.date,
+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)),
+ 0
+ from public.contact_notes cn
+ where (resources is null or 'contact_notes' = any(resources)) and cn.fts @@ tsq
+ order by cn.date desc nulls last
+ limit row_limit)
+ union all
+ (select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)),
+ 0
+ from public.deal_notes dn
+ join public.deals nd on nd.id = dn.deal_id
+ where (resources is null or 'deal_notes' = any(resources)) and nd.archived_at is null and dn.fts @@ tsq
+ order by dn.date desc nulls last
+ limit row_limit)
+ ) results
+ order by rank desc, date desc nulls last;
end
$function$
;
diff --git a/supabase/schemas/08_search.sql b/supabase/schemas/08_search.sql
index 396a2e3b..9853b320 100644
--- a/supabase/schemas/08_search.sql
+++ b/supabase/schemas/08_search.sql
@@ -38,13 +38,6 @@ CREATE OR REPLACE FUNCTION "public"."search_query"("query" "text") RETURNS "tsqu
where word <> ''
$$;
--- Same as search_query(), restricted to the words weighted A in a document:
--- the record's name for companies, contacts and deals.
-CREATE OR REPLACE FUNCTION "public"."search_name_query"("query" "text") RETURNS "tsquery"
- LANGUAGE "sql" IMMUTABLE STRICT PARALLEL SAFE
- SET "search_path" TO ''
- AS $$ select replace(public.search_query(query)::text, ':*', ':*A')::tsquery $$;
-
CREATE OR REPLACE FUNCTION "public"."search_attachment_titles"("attachments" "jsonb"[]) RETURNS "text"
LANGUAGE "sql" IMMUTABLE PARALLEL SAFE
SET "search_path" TO ''
@@ -93,7 +86,9 @@ create index deal_notes_fts_idx on public.deal_notes using gin (fts);
-- A word found in most rows (a common word, a 2-letter prefix) makes the GIN
-- path fetch and sort every match. Walking a date index backwards instead stops
-- at the first max_results matches. The planner picks between the two per
--- query, which needs fine-grained lexeme statistics on the large tables.
+-- query, which needs fine-grained lexeme statistics on the large tables. This
+-- only applies to tasks and notes: global_search() ranks the other resources
+-- by relevance, which needs every match.
create index contacts_first_seen_idx on public.contacts using btree (first_seen desc nulls last);
create index tasks_open_created_at_idx on public.tasks using btree (created_at desc) where done_date is null;
create index contact_notes_date_idx on public.contact_notes using btree (date desc nulls last);
@@ -104,125 +99,98 @@ alter table public.tasks alter column fts set statistics 10000;
alter table public.contact_notes alter column fts set statistics 10000;
alter table public.deal_notes alter column fts set statistics 10000;
--- Each branch takes its own newest max_results matches (at most 200), so the
+-- Companies, contacts and deals are ranked by relevance (ts_rank): their name
+-- is weighted A in fts, so a contact named John Doe ranks before one whose
+-- background mentions John Doe. Ties, tasks and notes go newest first.
+--
+-- Each branch takes its own max_results best matches (at most 200), so the
-- union never holds more than 6 * max_results rows, and the lookups that build
-- display labels only run on those. The cap is per resource, not overall: an
-- old contact must not be crowded out by newer notes that mention its name.
-- `content` carries the searched fields in their original form, so the client
--- can show and highlight where the words matched. The SQL is built per call
--- with the tsquery inlined as a literal: with a parameter the planner could not
--- tell a rare word (use the GIN index) from a common one (walk the date index).
+-- can show and highlight where the words matched.
--
--- Records whose name matches every query word (a contact named John Doe) rank
--- before those matching elsewhere (a contact whose background mentions John
--- Doe), then newest first. Companies, contacts and deals run their branch
--- twice, once for name matches and once for the others, so each half can still
--- walk the date index: testing the name on every match is slow for a common
--- word.
+-- force_custom_plan plans each call with the actual query: with a generic plan
+-- the planner could not tell a rare word (use the GIN index) from a common one
+-- (walk the date index), and could not skip the resources left out.
CREATE OR REPLACE FUNCTION "public"."global_search"("query" "text", "resources" "text"[] DEFAULT NULL::"text"[], "max_results" integer DEFAULT 50) RETURNS TABLE("resource" "text", "record_id" bigint, "title" "text", "subtitle" "text", "contact_id" bigint, "deal_id" bigint, "date" timestamp with time zone, "content" "text")
LANGUAGE "plpgsql" STABLE
SET "search_path" TO ''
- AS $_$
+ SET "plan_cache_mode" TO 'force_custom_plan'
+ AS $$
+#variable_conflict use_column
declare
tsq tsquery := public.search_query(query);
- name_tsq tsquery := public.search_name_query(query);
- -- Placeholders: %1$L is the query, %2$s the row limit. Branches of named
- -- resources also take %3$s, whether the name matches, and %4$s, the
- -- matching condition on fts.
- branch_templates constant jsonb := jsonb_build_object(
- 'companies', $q$
- select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at,
- concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr),
- %3$s as is_name_match
- from public.companies c
- where %4$s
- order by c.created_at desc
- limit %2$s $q$,
- 'contacts', $q$
- select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
- (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
- concat_ws(' · ', co.title, co.background,
- (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
- (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)),
- %3$s as is_name_match
- from public.contacts co
- where %4$s
- order by co.first_seen desc nulls last
- limit %2$s $q$,
- 'deals', $q$
- select 'deals', d.id, d.name,
- (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
- concat_ws(' · ', variadic d.categories || d.description),
- %3$s as is_name_match
- from public.deals d
- where d.archived_at is null and %4$s
- order by d.created_at desc
- limit %2$s $q$,
- 'tasks', $q$
- select 'tasks', t.id, left(t.text, 200),
- (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
- t.contact_id, null::bigint, t.created_at,
- concat_ws(' · ', t.text, t.type), false as is_name_match
- from public.tasks t
- where t.done_date is null and t.fts @@ %1$L::tsquery
- order by t.created_at desc
- limit %2$s $q$,
- 'contact_notes', $q$
- select 'contact_notes', cn.id, left(cn.text, 200),
- (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
- cn.contact_id, null::bigint, cn.date,
- concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)), false as is_name_match
- from public.contact_notes cn
- where cn.fts @@ %1$L::tsquery
- order by cn.date desc nulls last
- limit %2$s $q$,
- 'deal_notes', $q$
- select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
- concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)), false as is_name_match
- from public.deal_notes dn
- join public.deals nd on nd.id = dn.deal_id
- where nd.archived_at is null and dn.fts @@ %1$L::tsquery
- order by dn.date desc nulls last
- limit %2$s $q$
- );
- -- A named resource's branch runs once with each condition
- named_resources constant text[] := array['companies', 'contacts', 'deals'];
- name_match constant text := format('fts @@ %L::tsquery', name_tsq);
- other_match constant text := format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq, name_tsq);
row_limit constant integer := least(coalesce(max_results, 50), 200);
- columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_name_match';
- branches text[];
begin
if tsq is null or row_limit < 1 then
return;
end if;
- select array_agg(case
- when b.name = any(named_resources) then format(
- '(select * from ((%s) union all (%s)) halves(%s) order by is_name_match desc, date desc nulls last limit %s)',
- format(template, tsq, row_limit, 'true', name_match),
- format(template, tsq, row_limit, 'false', other_match),
- columns,
- row_limit)
- else format('(%s)', format(template, tsq, row_limit))
- end)
- into branches
- from jsonb_each_text(branch_templates) as b(name, template)
- where resources is null or b.name = any(resources);
-
- if branches is null then
- return;
- end if;
-
- return query execute format(
- 'select resource, record_id, title, subtitle, contact_id, deal_id, date, content
- from (%s) results(%s)
- order by is_name_match desc, date desc nulls last',
- array_to_string(branches, ' union all '),
- columns
- );
+ return query
+ select resource, record_id, title, subtitle, contact_id, deal_id, date, content
+ from (
+ (select 'companies' as resource, c.id as record_id, c.name as title, c.sector as subtitle,
+ null::bigint as contact_id, null::bigint as deal_id, c.created_at as date,
+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr) as content,
+ ts_rank(c.fts, tsq) as rank
+ from public.companies c
+ where (resources is null or 'companies' = any(resources)) and c.fts @@ tsq
+ order by rank desc, c.created_at desc
+ limit row_limit)
+ union all
+ (select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),
+ (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,
+ concat_ws(' · ', co.title, co.background,
+ (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),
+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)),
+ ts_rank(co.fts, tsq) as rank
+ from public.contacts co
+ where (resources is null or 'contacts' = any(resources)) and co.fts @@ tsq
+ order by rank desc, co.first_seen desc nulls last
+ limit row_limit)
+ union all
+ (select 'deals', d.id, d.name,
+ (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,
+ concat_ws(' · ', variadic d.categories || d.description),
+ ts_rank(d.fts, tsq) as rank
+ from public.deals d
+ where (resources is null or 'deals' = any(resources)) and d.archived_at is null and d.fts @@ tsq
+ order by rank desc, d.created_at desc
+ limit row_limit)
+ union all
+ (select 'tasks', t.id, left(t.text, 200),
+ (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),
+ t.contact_id, null::bigint, t.created_at,
+ concat_ws(' · ', t.text, t.type),
+ 0
+ from public.tasks t
+ where (resources is null or 'tasks' = any(resources)) and t.done_date is null and t.fts @@ tsq
+ order by t.created_at desc
+ limit row_limit)
+ union all
+ (select 'contact_notes', cn.id, left(cn.text, 200),
+ (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),
+ cn.contact_id, null::bigint, cn.date,
+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)),
+ 0
+ from public.contact_notes cn
+ where (resources is null or 'contact_notes' = any(resources)) and cn.fts @@ tsq
+ order by cn.date desc nulls last
+ limit row_limit)
+ union all
+ (select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,
+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)),
+ 0
+ from public.deal_notes dn
+ join public.deals nd on nd.id = dn.deal_id
+ where (resources is null or 'deal_notes' = any(resources)) and nd.archived_at is null and dn.fts @@ tsq
+ order by dn.date desc nulls last
+ limit row_limit)
+ ) results
+ order by rank desc, date desc nulls last;
end
-$_$;
+$$;
revoke execute on function public.global_search(text, text[], integer) from public, anon;
grant execute on function public.global_search(text, text[], integer) to authenticated, service_role;