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
feat(search): content-aware result ranking
perfectra1n1bdbbe5fd35d
diff --git a/packages/trilium-core/src/services/search/search_result.spec.ts b/packages/trilium-core/src/services/search/search_result.spec.tsindex 5ef29ed702..fb1590020c 100644--- a/packages/trilium-core/src/services/search/search_result.spec.ts+++ b/packages/trilium-core/src/services/search/search_result.spec.ts@@ -4,6 +4,7 @@ import becca from "../../becca/becca.js";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";let rootNote: NoteBuilder;@@ -206,6 +207,113 @@ describe("SearchResult", () => {});});+ describe("computeScore - content-aware scoring", () => {+ /** A content-only note whose title/path never matches the query, so the+ * score reflects only the supplied content match. */+ function contentOnlyScore(contentMatch: ContentMatchQuality | undefined): number {+ const target = note("Zzz Unrelated Title");+ rootNote.child(target);+ const result = resultFor(target);+ // Query tokens deliberately absent from the title; fuzzy disabled.+ result.computeScore("qqzzxx", ["qqzzxx"], false, contentMatch);+ return result.score;+ }++ it("adds the tier weight for a single matched token", () => {+ const expectations: [ContentMatchTier, boolean, number][] = [+ ["substring", false, 15],+ ["word_prefix", false, 30],+ ["exact_word", false, 60],+ ["proximity", false, 80],+ ["proximity", true, 100],+ ["exact_phrase", false, 150],+ ["fuzzy", false, 5]+ ];++ for (const [tier, inOrder, expected] of expectations) {+ expect(contentOnlyScore({ tier, matchedTokenCount: 1, inOrder })).toBe(expected);+ }+ });++ it("awards a per-token bonus beyond the first token, capped at five tokens", () => {+ expect(contentOnlyScore({ tier: "substring", matchedTokenCount: 1, inOrder: false })).toBe(15);+ expect(contentOnlyScore({ tier: "substring", matchedTokenCount: 2, inOrder: false })).toBe(20);+ expect(contentOnlyScore({ tier: "substring", matchedTokenCount: 5, inOrder: false })).toBe(35);+ // Sixth+ token contributes nothing beyond the five-token cap.+ expect(contentOnlyScore({ tier: "substring", matchedTokenCount: 6, inOrder: false })).toBe(35);+ });++ it("leaves legacy scores unchanged when no content match is supplied", () => {+ const target = note("Vienna");+ rootNote.child(target);++ const withUndefined = resultFor(target);+ withUndefined.computeScore("vienna", ["vienna"], false, undefined);++ const withoutArg = resultFor(target);+ withoutArg.computeScore("vienna", ["vienna"], false);++ expect(withUndefined.score).toBe(withoutArg.score);+ // Exact title match dominates; no content contribution applied.+ expect(withUndefined.score).toBeGreaterThanOrEqual(2000);+ });++ it("keeps the maximum content contribution below the title-word-match weight (300)", () => {+ const tiers: ContentMatchTier[] = [+ "fuzzy",+ "substring",+ "word_prefix",+ "exact_word",+ "proximity",+ "exact_phrase"+ ];++ let maxContent = 0;+ for (const tier of tiers) {+ // matchedTokenCount 5 and inOrder maximise the contribution.+ maxContent = Math.max(maxContent, contentOnlyScore({ tier, matchedTokenCount: 5, inOrder: true }));+ }++ // exact_phrase (150) + 4-token bonus (20) = 170 is the ceiling; the+ // in-order bonus never applies to exact_phrase, so it stays under 190.+ expect(maxContent).toBe(170);+ expect(maxContent).toBeLessThan(300); // TITLE_WORD_MATCH+ });++ it("ranks an exact-title note above any content-only match for the same query", () => {+ const titled = note("sync");+ const bodyOnly = note("Unrelated");+ rootNote.child(titled).child(bodyOnly);++ const titleResult = resultFor(titled);+ titleResult.computeScore("sync", ["sync"], false);++ const contentResult = resultFor(bodyOnly);+ contentResult.computeScore("sync", ["sync"], false, { tier: "exact_phrase", matchedTokenCount: 5, inOrder: true });++ expect(titleResult.score).toBeGreaterThan(contentResult.score);+ });++ it("feeds a fuzzy content contribution into the fuzzy-score cap", () => {+ // Build a query whose many tokens each fuzzy-match a distinct title word,+ // driving the fuzzy budget to MAX_TOTAL_FUZZY_SCORE. Once the budget is+ // exhausted, an additional fuzzy content match must contribute nothing.+ const titleWords = Array.from({ length: 300 }, (_, i) => `wordaaa${i}`);+ const tokens = Array.from({ length: 300 }, (_, i) => `wordaab${i}`); // edit distance 1 each+ const target = note(titleWords.join(" "));+ rootNote.child(target);++ const withFuzzyContent = resultFor(target);+ withFuzzyContent.computeScore("nomatchquery", tokens, true, { tier: "fuzzy", matchedTokenCount: 5, inOrder: false });++ const withoutContent = resultFor(target);+ withoutContent.computeScore("nomatchquery", tokens, true, undefined);++ // The fuzzy budget was already capped, so the fuzzy content match added 0.+ expect(withFuzzyContent.score).toBe(withoutContent.score);+ });+ });+describe("computeScore - fuzzy matching", () => {it("awards a fuzzy title score for a near-miss query only when fuzzy matching is enabled", () => {const target = note("Vienna");diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.tsindex 3f16ef3da5..eb913d7c55 100644--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@ -1,5 +1,6 @@import becca from "../../becca/becca.js";import becca_service from "../../becca/becca_service.js";+import type { ContentMatchQuality } from "./match_quality.js";import {calculateOptimizedEditDistance,FUZZY_SEARCH_CONFIG,@@ -22,6 +23,18 @@ const SCORE_WEIGHTS = {TITLE_FACTOR: 2.0,PATH_FACTOR: 0.3,HIDDEN_NOTE_PENALTY: 3,+ // Content match weights (body content quality), by tier. The maximum possible+ // content contribution is exact_phrase (150) + the four-token bonus (4 x 5 = 20)+ // = 170, which stays below TITLE_WORD_MATCH (300) by construction so an+ // exact/prefix/word title match always outranks a content-only match.+ CONTENT_EXACT_PHRASE: 150,+ CONTENT_PROXIMITY: 80,+ CONTENT_IN_ORDER_BONUS: 20, // only when tier === "proximity" && inOrder+ CONTENT_EXACT_WORD: 60,+ CONTENT_WORD_PREFIX: 30,+ CONTENT_SUBSTRING: 15,+ CONTENT_FUZZY: 5,+ CONTENT_TOKEN_COUNT_BONUS: 5, // per distinct matched token beyond the first, capped at 5 tokens total// Score caps to prevent fuzzy matches from outranking exact matchesMAX_FUZZY_SCORE_PER_TOKEN: 3, // Cap fuzzy token contributions to stay below exact matchesMAX_FUZZY_TOKEN_LENGTH_MULTIPLIER: 3, // Limit token length impact for fuzzy matches@@ -55,7 +68,7 @@ class SearchResult {return this.notePathArray[this.notePathArray.length - 1];}- computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true) {+ computeScore(fulltextQuery: string, tokens: string[], enableFuzzyMatching: boolean = true, contentMatch?: ContentMatchQuality) {this.score = 0;this.fuzzyScore = 0; // Reset fuzzy score tracking@@ -87,11 +100,61 @@ class SearchResult {this.addScoreForStrings(tokens, note.title, SCORE_WEIGHTS.TITLE_FACTOR, enableFuzzyMatching);this.addScoreForStrings(tokens, this.notePathTitle, SCORE_WEIGHTS.PATH_FACTOR, enableFuzzyMatching);+ // Add score for how well the note's body content matched the query.+ if (contentMatch) {+ this.addContentScore(contentMatch);+ }+if (note.isInHiddenSubtree()) {this.score = this.score / SCORE_WEIGHTS.HIDDEN_NOTE_PENALTY;}}+ /**+ * Adds the content-match contribution for a note's body. The tier weight plus a+ * per-token bonus (capped at five tokens) is bounded well below the title+ * weights, so content quality can reorder equally-titled notes without ever+ * overtaking a title match. Fuzzy-tier content counts toward the shared fuzzy+ * budget so it cannot help a fuzzy result outrank an exact one.+ */+ private addContentScore(contentMatch: ContentMatchQuality) {+ let base = 0;+ switch (contentMatch.tier) {+ case "exact_phrase":+ base = SCORE_WEIGHTS.CONTENT_EXACT_PHRASE;+ break;+ case "proximity":+ base = SCORE_WEIGHTS.CONTENT_PROXIMITY + (contentMatch.inOrder ? SCORE_WEIGHTS.CONTENT_IN_ORDER_BONUS : 0);+ break;+ case "exact_word":+ base = SCORE_WEIGHTS.CONTENT_EXACT_WORD;+ break;+ case "word_prefix":+ base = SCORE_WEIGHTS.CONTENT_WORD_PREFIX;+ break;+ case "substring":+ base = SCORE_WEIGHTS.CONTENT_SUBSTRING;+ break;+ case "fuzzy":+ base = SCORE_WEIGHTS.CONTENT_FUZZY;+ break;+ }++ const cappedTokens = Math.min(contentMatch.matchedTokenCount, 5);+ const tokenBonus = SCORE_WEIGHTS.CONTENT_TOKEN_COUNT_BONUS * Math.max(0, cappedTokens - 1);+ let contentScore = base + tokenBonus;++ if (contentMatch.tier === "fuzzy") {+ if (this.fuzzyScore >= SCORE_WEIGHTS.MAX_TOTAL_FUZZY_SCORE) {+ contentScore = 0;+ } else {+ this.fuzzyScore += contentScore;+ }+ }++ this.score += contentScore;+ }+addScoreForStrings(tokens: string[], str: string, factor: number, enableFuzzyMatching: boolean = true) {// Tokenize (strip boundary punctuation) so a chunk like "(sync)" scores as// an exact token match for "sync" rather than only a contains match.diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 3da446e5d9..ddc9a254a3 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -290,6 +290,10 @@ function performSearch(expression: Expression, searchContext: SearchContext, enaconst originalFuzzyMatching = searchContext.enableFuzzyMatching;searchContext.enableFuzzyMatching = enableFuzzyMatching;+ // Each progressive phase re-executes the expression tree, so clear content-match+ // records first — otherwise phase-2 (fuzzy) records would mix with phase-1 ones.+ searchContext.contentMatches.clear();+const noteSet = expression.execute(allNoteSet, executionContext, searchContext);const searchResults = noteSet.notes.map((note) => {@@ -303,7 +307,7 @@ function performSearch(expression: Expression, searchContext: SearchContext, ena});for (const res of searchResults) {- res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching);+ res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens, enableFuzzyMatching, searchContext.contentMatches.get(res.noteId));}// Restore original fuzzy setting