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): rank autocomplete results in two passes
Elian Doranab6dc34c1523
diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex e635143747..3ca0360a61 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -87,6 +87,7 @@ class BNote extends AbstractBeccaEntity<BNote> {__searchableTitleCache!: SearchableTitle | null;private __attributeCache!: BAttribute[] | null;+ private __isArchivedCache!: boolean | null;private __inheritableAttributeCache!: BAttribute[] | null;private __ancestorCache!: BNote[] | null;@@ -148,6 +149,7 @@ class BNote extends AbstractBeccaEntity<BNote> {this.children = [];this.ownedAttributes = [];this.__attributeCache = null;+ this.__isArchivedCache = null;this.__inheritableAttributeCache = null;this.targetRelations = [];@@ -718,7 +720,13 @@ class BNote extends AbstractBeccaEntity<BNote> {}get isArchived() {- return this.hasAttribute("label", "archived");+ // Ranking a note path tests this for every note on it, so the attribute walk is cached+ // alongside the attributes it reads.+ if (this.__isArchivedCache === null) {+ this.__isArchivedCache = this.hasAttribute("label", "archived");+ }++ return this.__isArchivedCache;}areAllNotePathsArchived() {@@ -830,6 +838,7 @@ class BNote extends AbstractBeccaEntity<BNote> {this.__searchableTitleCache = null;this.__attributeCache = null;+ this.__isArchivedCache = null;this.__inheritableAttributeCache = null;this.__ancestorCache = null;diff --git a/packages/trilium-core/src/services/search/search_context.ts b/packages/trilium-core/src/services/search/search_context.tsindex 45964b5906..44b8ebbae0 100644--- a/packages/trilium-core/src/services/search/search_context.ts+++ b/packages/trilium-core/src/services/search/search_context.ts@@ -25,6 +25,7 @@ class SearchContext {enableFuzzyMatching: boolean; // Controls whether fuzzy matching is enabled for this search phase/** When true, skip the two-phase fuzzy fallback and use the single-token fast path. */autocomplete: boolean;+ rankInTwoPasses: boolean;highlightedTokens: string[];/*** Subset of {@link highlightedTokens} that came from the `%=` (regex) operator@@ -62,6 +63,7 @@ class SearchContext {this.debugInfo = null;this.fuzzyAttributeSearch = !!params.fuzzyAttributeSearch;this.autocomplete = !!params.autocomplete;+ this.rankInTwoPasses = !!params.rankInTwoPasses;try {this.enableFuzzyMatching = optionService.getOptionBool("searchEnableFuzzyMatching");} catch {diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.tsindex 8a042aab8a..ae73cd3345 100644--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@ -72,9 +72,9 @@ export function precomputeScoringTerms(fulltextQuery: string, tokens: string[]):class SearchResult {notePathArray: string[];score: number;- notePathTitle: string;- /** The per-segment titles `notePathTitle` joins, kept so scoring can tokenize them separately. */- private pathTitleSegments: string[];+ private segmentTitles?: SegmentTitleCache;+ private __pathTitleSegments?: string[];+ private __notePathTitle?: string;highlightedNotePathTitle?: string;contentSnippet?: string;highlightedContentSnippet?: string;@@ -84,12 +84,31 @@ class SearchResult {constructor(notePathArray: string[], segmentTitles?: SegmentTitleCache) {this.notePathArray = notePathArray;- this.pathTitleSegments = becca_service.getNoteTitleArrayForPath(notePathArray, segmentTitles);- this.notePathTitle = this.pathTitleSegments.join(" › ");+ this.segmentTitles = segmentTitles;this.score = 0;this.fuzzyScore = 0;}+ /**+ * Resolved on demand. Ranking scores far more results than it returns, and only the ones that+ * survive to the second pass need their path spelled out.+ */+ private get pathTitleSegments(): string[] {+ if (!this.__pathTitleSegments) {+ this.__pathTitleSegments = becca_service.getNoteTitleArrayForPath(this.notePathArray, this.segmentTitles);+ }++ return this.__pathTitleSegments;+ }++ get notePathTitle(): string {+ if (this.__notePathTitle === undefined) {+ this.__notePathTitle = this.pathTitleSegments.join(" › ");+ }++ return this.__notePathTitle;+ }+get notePath() {return this.notePathArray.join("/");}@@ -98,7 +117,7 @@ class SearchResult {return this.notePathArray[this.notePathArray.length - 1];}- computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true, contentMatch?: ContentMatchQuality, terms?: ScoringTerms) {+ computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true, contentMatch?: ContentMatchQuality, terms?: ScoringTerms, includePathScore: boolean = true) {this.score = 0;this.fuzzyScore = 0; // Reset fuzzy score tracking@@ -128,7 +147,9 @@ class SearchResult {// Add scores for token matchesthis.addScoreForChunks(titleWords, tokens, SCORE_WEIGHTS.TITLE_FACTOR, enableFuzzyMatching, normalizedTokens);- this.addScoreForChunks(this.getPathWords(pathSegmentWords), tokens, SCORE_WEIGHTS.PATH_FACTOR, enableFuzzyMatching, normalizedTokens);+ if (includePathScore) {+ this.addScoreForChunks(this.getPathWords(pathSegmentWords), tokens, SCORE_WEIGHTS.PATH_FACTOR, enableFuzzyMatching, normalizedTokens);+ }// Add score for how well the note's body content matched the query.if (contentMatch) {diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 7ea3059e3b..ac30ff9f9d 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -320,6 +320,13 @@ function findResultsWithExpression(expression: Expression, searchContext: Searchreturn mergeExactAndFuzzyResults(exactResults, fuzzyResults);}+/**+ * How many results the second ranking pass keeps. Generous against the 25 a dropdown shows, so the+ * path contribution -- weighted at {@link SCORE_WEIGHTS.PATH_FACTOR} and worth a few points against+ * title weights in the hundreds -- cannot promote anything from outside it into what is returned.+ */+const RANK_SHORTLIST = 200;+function performSearch(expression: Expression, searchContext: SearchContext, enableFuzzyMatching: boolean): SearchResult[] {const allNoteSet = becca.getAllNoteSet();@@ -352,15 +359,29 @@ function performSearch(expression: Expression, searchContext: SearchContext, ena// Derived once rather than per result: every match is scored against the same query.const scoringTerms = precomputeScoringTerms(searchContext.fulltextQuery, searchContext.highlightedTokens);+ // With a rank limit, score without the path first. That leaves every result's path unresolved,+ // which is the bulk of the per-result work, and only the shortlist pays for it below.+ const twoPass = searchContext.rankInTwoPasses && searchResults.length > RANK_SHORTLIST;+for (const res of searchResults) {- res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId), scoringTerms);+ res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId), scoringTerms, !twoPass);+ }++ let ranked = searchResults;++ if (twoPass) {+ ranked = searchResults.sort((a, b) => b.score - a.score).slice(0, RANK_SHORTLIST);++ for (const res of ranked) {+ res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId), scoringTerms);+ }}// Restore original fuzzy settingsearchContext.enableFuzzyMatching = originalFuzzyMatching;if (!noteSet.sorted) {- searchResults.sort((a, b) => {+ ranked.sort((a, b) => {if (a.score > b.score) {return -1;} else if (a.score < b.score) {@@ -377,7 +398,7 @@ function performSearch(expression: Expression, searchContext: SearchContext, ena});}- return searchResults;+ return ranked;}function mergeExactAndFuzzyResults(exactResults: SearchResult[], fuzzyResults: SearchResult[]): SearchResult[] {@@ -754,7 +775,9 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {includeHiddenNotes: true,fuzzyAttributeSearch: true,ignoreInternalAttributes: true,- ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId()+ ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId(),+ // Only the first `AUTOCOMPLETE_RESULT_LIMIT` results are ever read.+ rankInTwoPasses: true});const trimmed = findResultsWithQuery(query, searchContext).slice(0, AUTOCOMPLETE_RESULT_LIMIT);diff --git a/packages/trilium-core/src/services/search/services/types.ts b/packages/trilium-core/src/services/search/services/types.tsindex 60d00540c6..dfebc50b25 100644--- a/packages/trilium-core/src/services/search/services/types.ts+++ b/packages/trilium-core/src/services/search/services/types.ts@@ -23,4 +23,9 @@ export interface SearchParams {fuzzyAttributeSearch?: boolean;/** When true, skip the two-phase fuzzy fallback and use the single-token fast path. */autocomplete?: boolean;+ /**+ * Rank in two passes, keeping only the best results. Set by callers that show a fixed number of+ * results and never read the rest, so the full set is never fully ranked.+ */+ rankInTwoPasses?: boolean;}