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): propagate per-note content match quality
perfectra1n7ecc2d9dac5e
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.tsindex d6a60092f3..adc3719664 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts@@ -3,6 +3,7 @@ import type { NoteRow } from "@triliumnext/commons";import becca from "../../../becca/becca.js";import { getLog } from "../../log.js";import protectedSessionService from "../../protected_session.js";+import { classifyContentMatch } from "../match_quality.js";import NoteSet from "../note_set.js";import type SearchContext from "../search_context.js";import {@@ -90,7 +91,7 @@ class NoteContentFulltextExp extends Expression {WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap', 'spreadsheet', 'llmChat')AND isDeleted = 0AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}`)) {- this.findInText(row, inputNoteSet, resultNoteSet);+ this.findInText(row, inputNoteSet, resultNoteSet, searchContext);}// For exact match with flatText, also search notes WITHOUT content (they may have matching attributes)@@ -204,7 +205,7 @@ class NoteContentFulltextExp extends Expression {return false;}- findInText({ noteId, isProtected, content, type, mime }: SearchRow, inputNoteSet: NoteSet, resultNoteSet: NoteSet) {+ findInText({ noteId, isProtected, content, type, mime }: SearchRow, inputNoteSet: NoteSet, resultNoteSet: NoteSet, searchContext: SearchContext) {if (!inputNoteSet.hasNoteId(noteId) || !(noteId in becca.notes)) {return;}@@ -235,72 +236,107 @@ class NoteContentFulltextExp extends Expression {}content = processedContent;+ const { matched, negation } = this.matchesContent(content, noteId);++ if (matched) {+ resultNoteSet.add(becca.notes[noteId]);+ // Record how well the content matched so scoring can rank body matches.+ // Negation (!=) matches are added because content does NOT contain the+ // query — there is no positive content match to record.+ if (!negation) {+ this.recordContentMatchQuality(noteId, content, searchContext);+ }+ }++ return content;+ }++ /**+ * Applies the operator's matching semantics for this note's content and+ * returns whether it matched and whether the match was a negation (!=).+ */+ private matchesContent(content: string, noteId: string): { matched: boolean; negation: boolean } {if (this.tokens.length === 1) {const [token] = this.tokens;- let matches = false;if (this.operator === "=") {- matches = this.containsExactWord(token, content);+ let matches = this.containsExactWord(token, content);// Also check flatText if enabled (includes attributes)if (!matches && this.flatText) {- const flatText = becca.notes[noteId].getFlatText();- matches = this.containsExactPhrase([token], flatText, true);+ matches = this.containsExactPhrase([token], becca.notes[noteId].getFlatText(), true);}- } else if (this.operator === "!=") {- matches = !this.containsExactWord(token, content);+ return { matched: matches, negation: false };+ }++ if (this.operator === "!=") {+ let matches = !this.containsExactWord(token, content);// For negation, check flatText tooif (matches && this.flatText) {- const flatText = becca.notes[noteId].getFlatText();- matches = !this.containsExactPhrase([token], flatText, true);+ matches = !this.containsExactPhrase([token], becca.notes[noteId].getFlatText(), true);}+ return { matched: matches, negation: true };}- if (- matches ||+ const matched =(this.operator === "*=" && content.endsWith(token)) ||(this.operator === "=*" && content.startsWith(token)) ||(this.operator === "*=*" && content.includes(token)) ||(this.operator === "%=" && getRegex(token).test(content)) ||(this.operator === "~=" && this.matchesWithFuzzy(content, noteId)) ||- (this.operator === "~*" && this.fuzzyContainsToken(normalizeSearchText(token), normalizeSearchText(content)))- ) {- resultNoteSet.add(becca.notes[noteId]);- }- } else {- // Multi-token matching with fuzzy support and phrase proximity- if (this.operator === "~=" || this.operator === "~*") {- // Fuzzy phrase matching- if (this.matchesWithFuzzy(content, noteId)) {- resultNoteSet.add(becca.notes[noteId]);- }- } else if (this.operator === "=" || this.operator === "!=") {- // Exact phrase matching for = and !=- let matches = this.containsExactPhrase(this.tokens, content, false);+ (this.operator === "~*" && this.fuzzyContainsToken(normalizeSearchText(token), normalizeSearchText(content)));- // Also check flatText if enabled (includes attributes)- if (!matches && this.flatText) {- const flatText = becca.notes[noteId].getFlatText();- matches = this.containsExactPhrase(this.tokens, flatText, true);- }+ return { matched, negation: false };+ }- if ((this.operator === "=" && matches) ||- (this.operator === "!=" && !matches)) {- resultNoteSet.add(becca.notes[noteId]);- }- } else {- // Other operators: check all tokens present (any order)- const nonMatchingToken = this.tokens.find(- (token) =>- !this.tokenMatchesContent(token, content, noteId)- );-- if (!nonMatchingToken) {- resultNoteSet.add(becca.notes[noteId]);- }+ // Multi-token matching with fuzzy support and phrase proximity+ if (this.operator === "~=" || this.operator === "~*") {+ return { matched: this.matchesWithFuzzy(content, noteId), negation: false };+ }++ if (this.operator === "=" || this.operator === "!=") {+ // Exact phrase matching for = and !=+ let matches = this.containsExactPhrase(this.tokens, content, false);+ // Also check flatText if enabled (includes attributes)+ if (!matches && this.flatText) {+ matches = this.containsExactPhrase(this.tokens, becca.notes[noteId].getFlatText(), true);}++ if (this.operator === "=") {+ return { matched: matches, negation: false };+ }+ return { matched: !matches, negation: true };}- return content;+ // Other operators: check all tokens present (any order)+ const nonMatchingToken = this.tokens.find((token) => !this.tokenMatchesContent(token, content, noteId));+ return { matched: !nonMatchingToken, negation: false };+ }++ /**+ * Classifies how well this note's body content matched the query tokens and+ * records the result on the search context for scoring. An exact-operator+ * match that came from flat text (attributes) rather than the body is recorded+ * at the exact tier directly, since body classification would find nothing.+ */+ private recordContentMatchQuality(noteId: string, content: string, searchContext: SearchContext) {+ const normalizedTokens = this.tokens.flatMap((token) => tokenizeIntoWords(token));+ if (normalizedTokens.length === 0) {+ return;+ }++ let quality = classifyContentMatch(normalizedTokens, tokenizeIntoWords(content));++ if (!quality && this.operator === "=") {+ quality = {+ tier: normalizedTokens.length > 1 ? "exact_phrase" : "exact_word",+ matchedTokenCount: new Set(normalizedTokens).size,+ inOrder: false+ };+ }++ if (quality) {+ searchContext.recordContentMatch(noteId, quality);+ }}/**diff --git a/packages/trilium-core/src/services/search/match_quality.spec.ts b/packages/trilium-core/src/services/search/match_quality.spec.tsnew file mode 100644index 0000000000..6a9047b312--- /dev/null+++ b/packages/trilium-core/src/services/search/match_quality.spec.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "vitest";++import { betterQuality, classifyContentMatch, type ContentMatchTier, tierRank } from "./match_quality.js";++/** Convenience: tokenize a plain string into whitespace-separated words. */+function words(text: string): string[] {+ return text.split(/\s+/).filter((word) => word.length > 0);+}++describe("match_quality", () => {+ describe("tierRank", () => {+ it("orders tiers from weakest (fuzzy) to strongest (exact_phrase)", () => {+ const ordered: ContentMatchTier[] = [+ "fuzzy",+ "substring",+ "word_prefix",+ "exact_word",+ "proximity",+ "exact_phrase"+ ];++ for (let i = 1; i < ordered.length; i++) {+ expect(tierRank(ordered[i])).toBeGreaterThan(tierRank(ordered[i - 1]));+ }+ });+ });++ describe("betterQuality", () => {+ it("keeps the higher tier", () => {+ const a = { tier: "substring" as const, matchedTokenCount: 3, inOrder: false };+ const b = { tier: "exact_word" as const, matchedTokenCount: 1, inOrder: false };++ expect(betterQuality(a, b)).toBe(b);+ expect(betterQuality(b, a)).toBe(b);+ });++ it("breaks a tier tie by the higher matchedTokenCount", () => {+ const a = { tier: "exact_word" as const, matchedTokenCount: 2, inOrder: false };+ const b = { tier: "exact_word" as const, matchedTokenCount: 4, inOrder: false };++ expect(betterQuality(a, b)).toBe(b);+ expect(betterQuality(b, a)).toBe(b);+ });+ });++ describe("classifyContentMatch", () => {+ it("returns null when nothing matches", () => {+ expect(classifyContentMatch(["zzz"], words("alpha beta gamma"))).toBeNull();+ expect(classifyContentMatch([], words("alpha"))).toBeNull();+ expect(classifyContentMatch(["alpha"], [])).toBeNull();+ });++ it("classifies a consecutive multi-token run as exact_phrase", () => {+ const q = classifyContentMatch(["you", "and", "me"], words("i like you and me as a phrase"));++ expect(q?.tier).toBe("exact_phrase");+ expect(q?.matchedTokenCount).toBe(3);+ });++ it("classifies all tokens present within the proximity window as proximity", () => {+ // "you" and "me" are exact words 3 apart, but not consecutive.+ const q = classifyContentMatch(["you", "me"], words("you know it is me now"));++ expect(q?.tier).toBe("proximity");+ expect(q?.inOrder).toBe(true);+ expect(q?.matchedTokenCount).toBe(2);+ });++ it("marks proximity out of order when the tokens appear reversed", () => {+ const q = classifyContentMatch(["alpha", "beta"], words("beta then some words alpha"));++ expect(q?.tier).toBe("proximity");+ expect(q?.inOrder).toBe(false);+ });++ it("treats tokens exactly 10 words apart as proximity but 11 apart as exact_word", () => {+ const fillers = (n: number) => Array.from({ length: n }, (_, i) => `x${i}`);++ const tenApart = ["alpha", ...fillers(9), "beta"]; // beta at index 10+ const elevenApart = ["alpha", ...fillers(10), "beta"]; // beta at index 11++ expect(classifyContentMatch(["alpha", "beta"], tenApart)?.tier).toBe("proximity");+ expect(classifyContentMatch(["alpha", "beta"], elevenApart)?.tier).toBe("exact_word");+ });++ it("classifies a single exact word match as exact_word", () => {+ const q = classifyContentMatch(["sync"], words("please sync the notes"));++ expect(q?.tier).toBe("exact_word");+ expect(q?.matchedTokenCount).toBe(1);+ expect(q?.inOrder).toBe(false);+ });++ it("classifies a content word that starts with the token as word_prefix", () => {+ const q = classifyContentMatch(["combin"], words("the value is combined here"));++ expect(q?.tier).toBe("word_prefix");+ expect(q?.matchedTokenCount).toBe(1);+ });++ it("classifies a token embedded inside a content word as substring", () => {+ const q = classifyContentMatch(["ync"], words("the asynchronous flag"));++ expect(q?.tier).toBe("substring");+ expect(q?.matchedTokenCount).toBe(1);+ });++ it("counts distinct matched tokens even across different tiers", () => {+ // "you" exact, "menu" prefix-matches "me", "and" exact => 3 distinct matched tokens,+ // best tier is exact_word (not all tokens are exact words, so no proximity).+ const q = classifyContentMatch(["you", "and", "me"], words("the menu and you"));++ expect(q?.tier).toBe("exact_word");+ expect(q?.matchedTokenCount).toBe(3);+ });+ });+});diff --git a/packages/trilium-core/src/services/search/match_quality.ts b/packages/trilium-core/src/services/search/match_quality.tsnew file mode 100644index 0000000000..31cd090fa7--- /dev/null+++ b/packages/trilium-core/src/services/search/match_quality.ts@@ -0,0 +1,199 @@+import { FUZZY_SEARCH_CONFIG, wordsContainPhrase } from "./utils/text_utils.js";++/**+ * Quality tiers describing how well a note's body content matched the query,+ * ordered from weakest to strongest. Propagated from expression evaluation into+ * scoring so that a note whose body contains the exact query phrase outranks a+ * note that merely contains the individual words scattered around.+ */+export type ContentMatchTier = "fuzzy" | "substring" | "word_prefix" | "exact_word" | "proximity" | "exact_phrase";++export interface ContentMatchQuality {+ /** The best tier achieved for this note's content. */+ tier: ContentMatchTier;+ /** Number of distinct query tokens that matched at any tier (scoring caps this at 5). */+ matchedTokenCount: number;+ /** Proximity only: whether the tokens appeared in query order within the window. */+ inOrder: boolean;+}++const TIER_RANK: Record<ContentMatchTier, number> = {+ fuzzy: 0,+ substring: 1,+ word_prefix: 2,+ exact_word: 3,+ proximity: 4,+ exact_phrase: 5+};++/** Numeric rank of a tier; higher is a stronger match. */+export function tierRank(tier: ContentMatchTier): number {+ return TIER_RANK[tier];+}++/**+ * Returns the better of two content-match qualities: the higher tier wins, and+ * a tier tie is broken by the higher matched-token count. Used to merge multiple+ * matches recorded for the same note.+ */+export function betterQuality(a: ContentMatchQuality, b: ContentMatchQuality): ContentMatchQuality {+ const rankA = tierRank(a.tier);+ const rankB = tierRank(b.tier);++ if (rankA !== rankB) {+ return rankA > rankB ? a : b;+ }++ return b.matchedTokenCount > a.matchedTokenCount ? b : a;+}++/**+ * Classifies how well a set of already-normalized query tokens matches a note's+ * already-tokenized content words, returning the best tier plus how many distinct+ * tokens matched (at any tier). Returns null when nothing matched.+ *+ * This is a pure function: tokens and contentWords must already be normalized and+ * tokenized (e.g. via {@link tokenizeIntoWords}) by the caller. It never computes+ * edit distances — the "fuzzy" tier is recorded by callers when only fuzzy matching+ * succeeded.+ */+export function classifyContentMatch(tokens: string[], contentWords: string[]): ContentMatchQuality | null {+ if (tokens.length === 0 || contentWords.length === 0) {+ return null;+ }++ const filteredTokens = tokens.filter((token) => token.length > 0);+ // Distinct tokens preserve first-appearance order (Set iteration order).+ const distinctTokens = Array.from(new Set(filteredTokens));+ if (distinctTokens.length === 0) {+ return null;+ }++ // Map each exact content word to its sorted positions for proximity/phrase checks.+ const wordPositions = new Map<string, number[]>();+ contentWords.forEach((word, index) => {+ const positions = wordPositions.get(word);+ if (positions) {+ positions.push(index);+ } else {+ wordPositions.set(word, [index]);+ }+ });++ let anyExact = false;+ let anyPrefix = false;+ let allExact = true;+ let matchedTokenCount = 0;+ const positionLists: number[][] = [];++ for (const token of distinctTokens) {+ const exactPositions = wordPositions.get(token) ?? [];+ positionLists.push(exactPositions);++ if (exactPositions.length > 0) {+ anyExact = true;+ matchedTokenCount++;+ continue;+ }++ allExact = false;++ if (contentWords.some((word) => word.startsWith(token))) {+ anyPrefix = true;+ matchedTokenCount++;+ } else if (contentWords.some((word) => word.includes(token))) {+ matchedTokenCount++;+ }+ }++ if (matchedTokenCount === 0) {+ return null;+ }++ const maxSpan = FUZZY_SEARCH_CONFIG.MAX_PHRASE_PROXIMITY;+ let tier: ContentMatchTier;+ let inOrder = false;++ if (filteredTokens.length >= 2 && wordsContainPhrase(contentWords, filteredTokens)) {+ tier = "exact_phrase";+ } else if (distinctTokens.length >= 2 && allExact && withinProximityWindow(positionLists, maxSpan)) {+ tier = "proximity";+ inOrder = inOrderWithinWindow(positionLists, maxSpan);+ } else if (anyExact) {+ tier = "exact_word";+ } else if (anyPrefix) {+ tier = "word_prefix";+ } else {+ tier = "substring";+ }++ return { tier, matchedTokenCount, inOrder };+}++/**+ * True when there is a window of at most `maxSpan` word positions containing at+ * least one occurrence of every token's position list. Classic minimum-window+ * sweep over the merged, position-sorted occurrences.+ */+function withinProximityWindow(positionLists: number[][], maxSpan: number): boolean {+ const merged: { position: number; listIndex: number }[] = [];+ positionLists.forEach((positions, listIndex) => {+ for (const position of positions) {+ merged.push({ position, listIndex });+ }+ });+ merged.sort((a, b) => a.position - b.position);++ const need = positionLists.length;+ const counts = new Array<number>(need).fill(0);+ let have = 0;+ let left = 0;++ for (let right = 0; right < merged.length; right++) {+ if (counts[merged[right].listIndex]++ === 0) {+ have++;+ }++ while (have === need) {+ if (merged[right].position - merged[left].position <= maxSpan) {+ return true;+ }+ if (--counts[merged[left].listIndex] === 0) {+ have--;+ }+ left++;+ }+ }++ return false;+}++/**+ * True when one occurrence per token can be chosen in strictly increasing+ * position order (i.e. query order) with the whole run spanning at most `maxSpan`+ * words. Position lists across distinct tokens are disjoint, so strict increase+ * is safe.+ */+function inOrderWithinWindow(positionLists: number[][], maxSpan: number): boolean {+ const [firstPositions, ...restLists] = positionLists;++ for (const start of firstPositions) {+ let previous = start;+ let ok = true;++ for (const positions of restLists) {+ const next = positions.find((position) => position > previous);+ if (next === undefined) {+ ok = false;+ break;+ }+ previous = next;+ }++ if (ok && previous - start <= maxSpan) {+ return true;+ }+ }++ return false;+}diff --git a/packages/trilium-core/src/services/search/search_context.spec.ts b/packages/trilium-core/src/services/search/search_context.spec.tsindex 71921a5f35..9e1c252df9 100644--- a/packages/trilium-core/src/services/search/search_context.spec.ts+++ b/packages/trilium-core/src/services/search/search_context.spec.ts@@ -114,6 +114,39 @@ describe("SearchContext", () => {expect(ctx.enableFuzzyMatching).toBe(true);});+ describe("recordContentMatch", () => {+ it("starts with an empty contentMatches map", () => {+ const ctx = new SearchContext();++ expect(ctx.contentMatches.size).toBe(0);+ });++ it("stores a quality for a note and upgrades it only when a better one arrives", () => {+ const ctx = new SearchContext();++ ctx.recordContentMatch("note1", { tier: "substring", matchedTokenCount: 1, inOrder: false });+ expect(ctx.contentMatches.get("note1")?.tier).toBe("substring");++ // Higher tier wins.+ ctx.recordContentMatch("note1", { tier: "exact_phrase", matchedTokenCount: 2, inOrder: false });+ expect(ctx.contentMatches.get("note1")?.tier).toBe("exact_phrase");++ // Weaker tier does not downgrade the stored quality.+ ctx.recordContentMatch("note1", { tier: "word_prefix", matchedTokenCount: 5, inOrder: false });+ expect(ctx.contentMatches.get("note1")?.tier).toBe("exact_phrase");+ expect(ctx.contentMatches.get("note1")?.matchedTokenCount).toBe(2);+ });++ it("breaks a tier tie by keeping the higher matchedTokenCount", () => {+ const ctx = new SearchContext();++ ctx.recordContentMatch("note1", { tier: "exact_word", matchedTokenCount: 1, inOrder: false });+ ctx.recordContentMatch("note1", { tier: "exact_word", matchedTokenCount: 3, inOrder: false });++ expect(ctx.contentMatches.get("note1")?.matchedTokenCount).toBe(3);+ });+ });+describe("addError / hasError / getError", () => {it("records the first error and ignores subsequent ones", () => {const ctx = new SearchContext();diff --git a/packages/trilium-core/src/services/search/search_context.ts b/packages/trilium-core/src/services/search/search_context.tsindex 64e35a420c..8a029c5850 100644--- a/packages/trilium-core/src/services/search/search_context.ts+++ b/packages/trilium-core/src/services/search/search_context.ts@@ -2,6 +2,7 @@import hoistedNoteService from "../hoisted_note.js";import optionService from "../options.js";+import { betterQuality, type ContentMatchQuality } from "./match_quality.js";import type { SearchParams } from "./services/types.js";class SearchContext {@@ -27,6 +28,12 @@ class SearchContext {fulltextQuery: string;dbLoadNeeded: boolean;error: string | null;+ /**+ * Per-note content match quality recorded during expression evaluation and+ * consumed by scoring. Bounded memory: one small record per matched note.+ * Cleared at the start of each progressive search phase.+ */+ contentMatches: Map<string, ContentMatchQuality>;constructor(params: SearchParams = {}) {this.fastSearch = !!params.fastSearch;@@ -62,6 +69,16 @@ class SearchContext {// and some extra data needs to be loaded before executingthis.dbLoadNeeded = false;this.error = null;+ this.contentMatches = new Map();+ }++ /**+ * Records how well a note's content matched, merging with any existing record+ * for that note so the best quality wins (higher tier, then more tokens).+ */+ recordContentMatch(noteId: string, quality: ContentMatchQuality) {+ const existing = this.contentMatches.get(noteId);+ this.contentMatches.set(noteId, existing ? betterQuality(existing, quality) : quality);}addError(error: string) {