Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
perf(search): derive the query's normalized form once per search
Elian Doran9e3c90503c52
diff --git a/packages/trilium-core/src/services/search/search_result.spec.ts b/packages/trilium-core/src/services/search/search_result.spec.tsindex c527003398..6a4b68fc8d 100644--- a/packages/trilium-core/src/services/search/search_result.spec.ts+++ b/packages/trilium-core/src/services/search/search_result.spec.ts@@ -5,7 +5,7 @@ import BBranch from "../../becca/entities/bbranch.js";import BNote from "../../becca/entities/bnote.js";import { note, NoteBuilder } from "../../test/becca_mocking.js";import type { ContentMatchQuality, ContentMatchTier } from "./match_quality.js";-import SearchResult from "./search_result.js";+import SearchResult, { precomputeScoringTerms } from "./search_result.js";let rootNote: NoteBuilder;@@ -55,6 +55,23 @@ describe("SearchResult", () => {});});+ it("scores identically whether the query terms are precomputed or derived per result", () => {+ const target = note("Viena Café Notes");+ rootNote.child(target);++ const query = "café notes";+ const tokens = [ "café", "notes" ];++ const derived = resultFor(target);+ derived.computeScore(query, tokens, true);++ const hoisted = resultFor(target);+ hoisted.computeScore(query, tokens, true, undefined, precomputeScoringTerms(query, tokens));++ expect(hoisted.score).toBe(derived.score);+ expect(derived.score).toBeGreaterThan(0);+ });+describe("computeScore - title matching", () => {it("awards the exact-title bonus when the query equals the title", () => {const target = note("Austria");diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.tsindex eb913d7c55..374a4d054d 100644--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@ -42,6 +42,22 @@ const SCORE_WEIGHTS = {} as const;+/**+ * The query-side strings every result is scored against. They depend on the query alone, so+ * `performSearch` derives them once and hands the same bundle to every result.+ */+export interface ScoringTerms {+ normalizedQuery: string;+ normalizedTokens: string[];+}++export function precomputeScoringTerms(fulltextQuery: string, tokens: string[]): ScoringTerms {+ return {+ normalizedQuery: normalizeSearchText(fulltextQuery),+ normalizedTokens: tokens.map((token) => stripWordPunctuation(normalizeSearchText(token)))+ };+}+class SearchResult {notePathArray: string[];score: number;@@ -68,13 +84,13 @@ class SearchResult {return this.notePathArray[this.notePathArray.length - 1];}- computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true, contentMatch?: ContentMatchQuality) {+ computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true, contentMatch?: ContentMatchQuality, terms?: ScoringTerms) {this.score = 0;this.fuzzyScore = 0; // Reset fuzzy score trackingconst note = becca.notes[this.noteId];+ const { normalizedQuery, normalizedTokens } = terms ?? precomputeScoringTerms(fulltextQuery, tokens);// normalizeSearchText already lowercases — no need for .toLowerCase() first- const normalizedQuery = normalizeSearchText(fulltextQuery);const normalizedTitle = normalizeSearchText(note.title);// Note ID exact match, much higher score@@ -97,8 +113,8 @@ class SearchResult {}// Add scores for token matches- this.addScoreForStrings(tokens, note.title, SCORE_WEIGHTS.TITLE_FACTOR, enableFuzzyMatching);- this.addScoreForStrings(tokens, this.notePathTitle, SCORE_WEIGHTS.PATH_FACTOR, enableFuzzyMatching);+ this.addScoreForStrings(tokens, note.title, SCORE_WEIGHTS.TITLE_FACTOR, enableFuzzyMatching, normalizedTokens);+ this.addScoreForStrings(tokens, this.notePathTitle, SCORE_WEIGHTS.PATH_FACTOR, enableFuzzyMatching, normalizedTokens);// Add score for how well the note's body content matched the query.if (contentMatch) {@@ -155,13 +171,12 @@ class SearchResult {this.score += contentScore;}- addScoreForStrings(tokens: string[], str: string, factor: number, enableFuzzyMatching: boolean = true) {+ addScoreForStrings(tokens: string[], str: string, factor: number, enableFuzzyMatching: boolean = true, precomputedTokens?: string[]) {// Tokenize (strip boundary punctuation) so a chunk like "(sync)" scores as// an exact token match for "sync" rather than only a contains match.const chunks = tokenizeIntoWords(str);- // Pre-normalize and strip tokens once instead of per-chunk- const normalizedTokens = tokens.map(t => stripWordPunctuation(normalizeSearchText(t)));+ const normalizedTokens = precomputedTokens ?? tokens.map(t => stripWordPunctuation(normalizeSearchText(t)));let tokenScore = 0;for (const chunk of chunks) {diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 24e115bf2a..a4185ff0ee 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -13,7 +13,7 @@ import { isScriptingEnabled } from "../../scripting_guard.js";import { escapeHtml, escapeRegExp, normalizePreservingLength, unescapeHtml } from "../../utils/index.js";import type Expression from "../expressions/expression.js";import SearchContext from "../search_context.js";-import SearchResult from "../search_result.js";+import SearchResult, { precomputeScoringTerms } from "../search_result.js";import handleParens from "./handle_parens.js";import lex from "./lex.js";import parse from "./parse.js";@@ -348,8 +348,10 @@ function performSearch(expression: Expression, searchContext: SearchContext, enareturn new SearchResult(notePathArray);});+ // Derived once rather than per result: every match is scored against the same query.+ const scoringTerms = precomputeScoringTerms(searchContext.fulltextQuery, searchContext.highlightedTokens);for (const res of searchResults) {- res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId));+ res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId), scoringTerms);}// Restore original fuzzy setting