From b0c02fc81f7fc90c71a905f22c20259f7fef65ce Mon Sep 17 00:00:00 2001 From: Tayeb Chlyah Date: Sat, 7 Mar 2026 13:03:40 +0400 Subject: [PATCH] feat(server) #3: sort search results by updated date then score --- server/modules/search/db/engine.js | 16 ++++++++++++++++ server/modules/search/postgres/engine.js | 14 ++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/server/modules/search/db/engine.js b/server/modules/search/db/engine.js index 04cb4280..1207d233 100644 --- a/server/modules/search/db/engine.js +++ b/server/modules/search/db/engine.js @@ -20,6 +20,7 @@ module.exports = { * @param {Object} opts Additional options */ async query(q, opts) { + const normalizedQuery = q.toLowerCase() const results = await WIKI.models.pages.query() .column('pages.id', 'title', 'description', 'path', 'localeCode as locale') .withGraphJoined('tags') // Adding page tags since they can be used to check resource access permissions @@ -46,6 +47,21 @@ module.exports = { } }) }) + .orderBy('pages.updatedAt', 'desc') + .orderByRaw(` + CASE + WHEN LOWER(title) = ? THEN 400 + WHEN LOWER(title) LIKE ? THEN 300 + WHEN LOWER(description) LIKE ? THEN 200 + WHEN LOWER(path) LIKE ? THEN 100 + ELSE 0 + END DESC + `, [ + normalizedQuery, + `%${normalizedQuery}%`, + `%${normalizedQuery}%`, + `%${normalizedQuery}%` + ]) .limit(WIKI.config.search.maxHits) return { results, diff --git a/server/modules/search/postgres/engine.js b/server/modules/search/postgres/engine.js index ffff750e..65658dfe 100644 --- a/server/modules/search/postgres/engine.js +++ b/server/modules/search/postgres/engine.js @@ -62,19 +62,21 @@ module.exports = { try { let suggestions = [] let qry = ` - SELECT id, path, locale, title, description, content - FROM "pagesVector", to_tsquery(?,?) query - WHERE (query @@ "tokens" OR path ILIKE ?) + SELECT pv.id, pv.path, pv.locale, pv.title, pv.description, pv.content + FROM "pagesVector" pv + INNER JOIN "pages" p ON p.path = pv.path AND p."localeCode" = pv.locale + CROSS JOIN to_tsquery(?,?) query + WHERE (query @@ pv.tokens OR pv.path ILIKE ?) ` - let qryEnd = `ORDER BY ts_rank(tokens, query) DESC` + let qryEnd = `ORDER BY p."updatedAt" DESC, ts_rank(pv.tokens, query) DESC` let qryParams = [this.config.dictLanguage, tsquery(q), `%${q.toLowerCase()}%`] if (opts.locale) { - qry = `${qry} AND locale = ?` + qry = `${qry} AND pv.locale = ?` qryParams.push(opts.locale) } if (opts.path) { - qry = `${qry} AND path ILIKE ?` + qry = `${qry} AND pv.path ILIKE ?` qryParams.push(`%${opts.path}`) } const results = await WIKI.models.knex.raw(`