From a717cb0645acebe582619b28a7beb99ceb6ee7ba Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 15 Oct 2026 23:07:59 -0400 Subject: [PATCH] fix: Retry Postgres search as a quoted query when there are no results (#14104) * fix: Retry Postgres search as a quoted query when there are no results * fix: Keep urls, length and stop words correct in quoted search retry --- .../server/PostgresSearchProvider.test.ts | 134 ++++++++++ .../server/PostgresSearchProvider.ts | 243 ++++++++++++++---- 2 files changed, 320 insertions(+), 57 deletions(-) diff --git a/plugins/search-postgres/server/PostgresSearchProvider.test.ts b/plugins/search-postgres/server/PostgresSearchProvider.test.ts index 884194afe3..4ba95af0c4 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.test.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.test.ts @@ -209,6 +209,25 @@ describe("PostgresSearchProvider", () => { }); expect(total).toBe(0); }); + + it("should retry as a quoted query when there are no results", async () => { + const team = await buildTeam(); + const collection = await buildCollection({ + teamId: team.id, + }); + const document = await buildDocument({ + teamId: team.id, + collectionId: collection.id, + title: "Platform", + text: "Container orchestration at scale", + }); + const { results } = await provider.searchForTeam(team, { + query: "chestration", + }); + expect(results.map((result) => result.document.id)).toEqual([ + document.id, + ]); + }); }); describe("#searchForUser", () => { @@ -913,6 +932,121 @@ describe("PostgresSearchProvider", () => { expect(total).toBe(1); }); + it("should retry as a quoted query when there are no results", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Platform", + text: "Container orchestration at scale", + }); + const { results, total } = await provider.searchForUser(user, { + query: "chestration", + }); + expect(total).toBe(1); + expect(results[0].document.id).toBe(document.id); + expect(results[0].context).toContain("orchestration"); + }); + + it("should keep urls separate when retrying as a quoted query", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Platform", + text: "Container orchestration, see https://example.com for more", + }); + const { results } = await provider.searchForUser(user, { + query: "https://example.com chestration", + }); + expect(results.map((result) => result.document.id)).toEqual([ + document.id, + ]); + }); + + it("should retry as a quoted query at the maximum query length", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + const query = "bc".repeat(PostgresSearchProvider.maxQueryLength / 2); + const document = await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Platform", + text: `a${query}`, + }); + const { results } = await provider.searchForUser(user, { query }); + expect(results.map((result) => result.document.id)).toEqual([ + document.id, + ]); + }); + + it("should not retry as a quoted query for short or stop word queries", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "Box", + text: "Gather together inside, where it is nothing", + }); + + for (const query of ["o", "the", "The ", "it is", "to", "in", "not"]) { + const { total } = await provider.searchForUser(user, { query }); + expect(total).toBe(0); + } + }); + + it("should not retry as a quoted query when paging past earlier results", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const collection = await buildCollection({ + teamId: team.id, + userId: user.id, + }); + await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "test", + text: "attestation", + }); + await buildDocument({ + teamId: team.id, + userId: user.id, + collectionId: collection.id, + title: "other", + text: "attestation", + }); + const { results, total } = await provider.searchForUser(user, { + query: "test", + offset: 1, + }); + expect(results.length).toBe(0); + expect(total).toBe(1); + }); + it("should return search results from group memberships", async () => { const team = await buildTeam(); const user = await buildUser({ teamId: team.id }); diff --git a/plugins/search-postgres/server/PostgresSearchProvider.ts b/plugins/search-postgres/server/PostgresSearchProvider.ts index de1844e820..ceeb0c0013 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.ts @@ -8,7 +8,7 @@ import type { Order, WhereOptions, } from "sequelize"; -import { Op, Sequelize } from "sequelize"; +import { Op, QueryTypes, Sequelize } from "sequelize"; import type { Filter } from "@shared/helpers/FilterHelper"; import type { SearchableModel } from "@shared/types"; import { DirectionFilter, SortFilter } from "@shared/types"; @@ -40,6 +40,28 @@ type RankedDocument = Document & { }; }; +type SearchWhere = WhereOptions & { + [Op.or]: WhereOptions[]; + [Op.and]: WhereOptions[]; +}; + +interface RankedSearchOptions { + where: SearchWhere; + query?: string; + sort?: SortFilter; + direction?: DirectionFilter; + usePopularityBoost?: boolean; + limit: number; + offset: number; +} + +interface RankedSearch { + query?: string; + results: RankedDocument[]; + where: SearchWhere; + replacements?: BindOrReplacements; +} + /** * Search provider that uses PostgreSQL full-text search via tsvector. * Indexing is handled by database triggers, so index/remove/updateMetadata @@ -235,17 +257,13 @@ export default class PostgresSearchProvider extends BaseSearchProvider { }); } - const findOptions = PostgresSearchProvider.buildFindOptions({ - query, - sort: options.sort, - direction: options.direction, - usePopularityBoost: options.usePopularityBoost, - }); - try { - const results = await PostgresSearchProvider.findRankedResults({ - findOptions, + const search = await PostgresSearchProvider.rankedSearch({ where, + query, + sort: options.sort, + direction: options.direction, + usePopularityBoost: options.usePopularityBoost, limit, offset, }); @@ -254,7 +272,7 @@ export default class PostgresSearchProvider extends BaseSearchProvider { const [documents, count] = await Promise.all([ Document.findAll({ where: { - id: map(results, "id"), + id: map(search.results, "id"), teamId: team.id, }, include: [ @@ -265,17 +283,17 @@ export default class PostgresSearchProvider extends BaseSearchProvider { ], }), PostgresSearchProvider.countResults({ - results, + results: search.results, limit, offset, - replacements: findOptions.replacements, - where, + replacements: search.replacements, + where: search.where, }), ]); return PostgresSearchProvider.buildResponse({ - query, - results, + query: search.query, + results: search.results, documents, count, }); @@ -355,16 +373,12 @@ export default class PostgresSearchProvider extends BaseSearchProvider { const where = await PostgresSearchProvider.buildWhere(user, options); - const findOptions = PostgresSearchProvider.buildFindOptions({ - query, - sort: options.sort, - direction: options.direction, - }); - try { - const results = await PostgresSearchProvider.findRankedResults({ - findOptions, + const search = await PostgresSearchProvider.rankedSearch({ where, + query, + sort: options.sort, + direction: options.direction, limit, offset, }); @@ -374,21 +388,21 @@ export default class PostgresSearchProvider extends BaseSearchProvider { Document.withMembershipScope(user.id, { includeDrafts: true }).findAll({ where: { teamId: user.teamId, - id: map(results, "id"), + id: map(search.results, "id"), }, }), PostgresSearchProvider.countResults({ - results, + results: search.results, limit, offset, - replacements: findOptions.replacements, - where, + replacements: search.replacements, + where: search.where, }), ]); return PostgresSearchProvider.buildResponse({ - query, - results, + query: search.query, + results: search.results, documents, count, }); @@ -446,6 +460,114 @@ export default class PostgresSearchProvider extends BaseSearchProvider { // PostgreSQL metadata lives in the same row as the document } + /** + * Runs the ranked search. When an unquoted query matches no documents, the + * search runs again with the query quoted, which is slower but also matches + * text that the full-text index does not. Queries shorter than two + * characters or made only of stop words are not retried. + */ + private static async rankedSearch( + options: RankedSearchOptions + ): Promise { + const search = await PostgresSearchProvider.runRankedSearch(options); + const { query } = options; + + if (search.results.length || !query || query.includes('"')) { + return search; + } + + // URLs already match as literal text, so only the remaining text is quoted. + const urls = getUrls(query); + const text = urls + .reduce((q, url) => q.replace(url, " "), query) + .replace(/\s+/g, " ") + .trim() + .slice(0, PostgresSearchProvider.maxQueryLength - 2) + .trim(); + + if ( + text.length < 2 || + (await PostgresSearchProvider.isOnlyStopWords(text)) + ) { + return search; + } + + // An empty page past the first can still follow earlier matches. + if (options.offset) { + const count = await PostgresSearchProvider.countResults({ + results: search.results, + limit: options.limit, + offset: options.offset, + replacements: search.replacements, + where: search.where, + }); + if (count) { + return search; + } + } + + return PostgresSearchProvider.runRankedSearch({ + ...options, + query: [`"${text}"`, ...urls].join(" "), + }); + } + + /** + * Returns true when the full-text parser keeps no terms from the query, as + * Postgres drops stop words. + */ + private static async isOnlyStopWords(query: string): Promise { + const [row] = await sequelizeReadOnly.query<{ nodes: number }>( + `SELECT numnode(to_tsquery('english', :query)) AS nodes`, + { + replacements: { + query: PostgresSearchProvider.webSearchQuery(query), + }, + type: QueryTypes.SELECT, + } + ); + return row?.nodes === 0; + } + + private static async runRankedSearch({ + where, + query, + sort, + direction, + usePopularityBoost, + limit, + offset, + }: RankedSearchOptions): Promise { + const findOptions = PostgresSearchProvider.buildFindOptions({ + query, + sort, + direction, + usePopularityBoost, + }); + const queryWhere: SearchWhere = query + ? { + ...where, + [Op.and]: [ + ...where[Op.and], + ...PostgresSearchProvider.buildQueryWhere(query), + ], + } + : where; + const results = await PostgresSearchProvider.findRankedResults({ + findOptions, + where: queryWhere, + limit, + offset, + }); + + return { + query, + results, + where: queryWhere, + replacements: findOptions.replacements, + }; + } + /** * Executes the ranked search query inside a transaction opened on the * read-replica connection, offloading the most expensive query from the @@ -632,10 +754,7 @@ export default class PostgresSearchProvider extends BaseSearchProvider { private static async buildWhere(model: User | Team, options: SearchOptions) { const teamId = model instanceof Team ? model.id : model.teamId; - const where: WhereOptions & { - [Op.or]: WhereOptions[]; - [Op.and]: WhereOptions[]; - } = { + const where: SearchWhere = { teamId, [Op.or]: [], [Op.and]: [ @@ -713,37 +832,47 @@ export default class PostgresSearchProvider extends BaseSearchProvider { where[Op.and].push(buildSearchWhere(filter)); } - if (options.query) { - // find words that look like urls, these should be treated separately as the postgres full-text - // index will generally not match them. - const likelyUrls = getUrls(options.query); + return where; + } - // remove likely urls from the query. - let limitedQuery = likelyUrls - .reduce((q, url) => q.replace(url, ""), options.query) - .slice(0, PostgresSearchProvider.maxQueryLength) - .trim(); + /** + * Builds the conditions that match documents to a search query. + * + * @param query the user search query. + * @returns the where conditions. + */ + private static buildQueryWhere(query: string): WhereOptions[] { + const conditions: WhereOptions[] = []; - // Extract quoted queries and add them to the where clause, up to a maximum of 3 total. - const quotedQueries = Array.from(limitedQuery.matchAll(/"([^"]*)"/g)).map( - (match) => match[1] - ); + // find words that look like urls, these should be treated separately as the postgres full-text + // index will generally not match them. + const likelyUrls = getUrls(query); - // remove quoted queries from the limited query - limitedQuery = limitedQuery.replace(/"([^"]*)"/g, ""); + // remove likely urls from the query. + let limitedQuery = likelyUrls + .reduce((q, url) => q.replace(url, ""), query) + .slice(0, PostgresSearchProvider.maxQueryLength) + .trim(); - const iLikeQueries = [...quotedQueries, ...likelyUrls].slice(0, 3); + // Extract quoted queries and add them to the where clause, up to a maximum of 3 total. + const quotedQueries = Array.from(limitedQuery.matchAll(/"([^"]*)"/g)).map( + (match) => match[1] + ); - for (const match of iLikeQueries) { - where[Op.and].push(PostgresSearchProvider.buildContainsMatch(match)); - } + // remove quoted queries from the limited query + limitedQuery = limitedQuery.replace(/"([^"]*)"/g, ""); - if (limitedQuery || iLikeQueries.length === 0) { - where[Op.and].push(PostgresSearchProvider.buildTextMatch(limitedQuery)); - } + const iLikeQueries = [...quotedQueries, ...likelyUrls].slice(0, 3); + + for (const match of iLikeQueries) { + conditions.push(PostgresSearchProvider.buildContainsMatch(match)); } - return where; + if (limitedQuery || iLikeQueries.length === 0) { + conditions.push(PostgresSearchProvider.buildTextMatch(limitedQuery)); + } + + return conditions; } /**