From 85fff6601d5e21bf8c4bd74597bb1f3434a8bfdd Mon Sep 17 00:00:00 2001 From: Felix Wotschofsky Date: Mon, 9 Dec 2024 23:55:52 +0100 Subject: [PATCH] =?UTF-8?q?Improve=20search=20suggestions=20=F0=9F=91=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/search.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/search.ts b/lib/search.ts index 6b0cb93..bbcce08 100644 --- a/lib/search.ts +++ b/lib/search.ts @@ -43,6 +43,23 @@ export const recordLookup = async (payload: LookupLogPayload) => { }; export const getSearchSuggestions = async (query: string) => { + const segments = query.split('.').filter(Boolean); + + const suggestions = await Promise.all( + // Limit to 2 segments to avoid abuse and keep results sensible + segments.slice(0, 2).map(async (_, i) => { + const querySegment = segments.slice(i).join('.'); + const suggestions = await getSearchSuggestionsForPrefix(querySegment); + const prefix = i === 0 ? '' : segments.slice(0, i).join('.'); + console.log({ querySegment, suggestions, prefix }); + return suggestions.map((s) => (prefix ? `${prefix}.${s}` : s)); + }), + ); + + return Array.from(new Set(suggestions.flat())); +}; + +export const getSearchSuggestionsForPrefix = async (prefix: string) => { if (!bigquery) { return []; } @@ -52,12 +69,12 @@ export const getSearchSuggestions = async (query: string) => { query: ` SELECT domain FROM ${tableName} - WHERE STARTS_WITH(domain, @query) + WHERE STARTS_WITH(domain, @prefix) ORDER BY count DESC LIMIT 5 `, params: { - query: query.toLowerCase(), + prefix: prefix.toLowerCase(), }, });