Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): fuzzy fallback for note body content

perfectra1n54b8adde7e6d
diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.spec.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.spec.ts
index 9d37999809..e15b2b6f44 100644
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.spec.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.spec.ts
@@ -57,3 +57,65 @@ describe("~* fuzzy-contains against note content", () => {
expect(matches("~*", "programing", "learn programming today")).toBe(true);
});
});
+
+describe("fuzzy fallback for note body content (A4)", () => {
+ beforeEach(() => {
+ becca.reset();
+ new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));
+ new BBranch({ branchId: "none_root", noteId: "root", parentNoteId: "none", notePosition: 10 });
+ });
+
+ function matchesWithFallback(tokens: string[], content: string, enableFuzzyMatching: boolean): boolean {
+ const note = getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Untitled",
+ content,
+ type: "text"
+ }).note);
+
+ const exp = new NoteContentFulltextExp("*=*", { tokens, flatText: true, fuzzyFallback: true });
+ const searchContext = new SearchContext();
+ searchContext.enableFuzzyMatching = enableFuzzyMatching;
+ const result = exp.execute(new NoteSet([note]), {}, searchContext);
+ return result.notes.some(n => n.noteId === note.noteId);
+ }
+
+ it("finds a body typo only when fuzzy matching is enabled (phase 2)", () => {
+ // "combinef" is one edit from the body word "combined" and not a substring.
+ expect(matchesWithFallback(["combinef"], "the values were combined here", false)).toBe(false);
+ expect(matchesWithFallback(["combinef"], "the values were combined here", true)).toBe(true);
+ });
+
+ it("does not trigger the fallback without the fuzzyFallback opt", () => {
+ const note = getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Untitled",
+ content: "the values were combined here",
+ type: "text"
+ }).note);
+
+ // Explicit *=* (no fuzzyFallback) stays substring-only even with fuzzy enabled.
+ const exp = new NoteContentFulltextExp("*=*", { tokens: ["combinef"], flatText: true });
+ const searchContext = new SearchContext();
+ searchContext.enableFuzzyMatching = true;
+ const result = exp.execute(new NoteSet([note]), {}, searchContext);
+
+ expect(result.notes.some(n => n.noteId === note.noteId)).toBe(false);
+ });
+
+ it("records a fuzzy content-match tier for a fallback hit", () => {
+ const note = getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Untitled",
+ content: "the values were combined here",
+ type: "text"
+ }).note);
+
+ const exp = new NoteContentFulltextExp("*=*", { tokens: ["combinef"], flatText: true, fuzzyFallback: true });
+ const searchContext = new SearchContext();
+ searchContext.enableFuzzyMatching = true;
+ exp.execute(new NoteSet([note]), {}, searchContext);
+
+ expect(searchContext.contentMatches.get(note.noteId)?.tier).toBe("fuzzy");
+ });
+});
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.ts
index adc3719664..94a9954b20 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
@@ -39,6 +39,14 @@ interface ConstructorOpts {
tokens: string[];
raw?: boolean;
flatText?: boolean;
+ /**
+ * When set, a note that fails normal `*=*` matching is retried with fuzzy
+ * matching against its body content (progressive phase 2 only, gated on
+ * {@link SearchContext.enableFuzzyMatching}). Only the default plain-query
+ * content expression built by parse's getFulltext sets this; explicit user
+ * operators never do.
+ */
+ fuzzyFallback?: boolean;
}
type SearchRow = Pick<NoteRow, "noteId" | "type" | "mime" | "content" | "isProtected">;
@@ -48,8 +56,9 @@ class NoteContentFulltextExp extends Expression {
tokens: string[];
private raw: boolean;
private flatText: boolean;
+ private fuzzyFallback: boolean;
- constructor(operator: string, { tokens, raw, flatText }: ConstructorOpts) {
+ constructor(operator: string, { tokens, raw, flatText, fuzzyFallback }: ConstructorOpts) {
super();
if (!operator || !tokens || !Array.isArray(tokens)) {
@@ -66,6 +75,7 @@ class NoteContentFulltextExp extends Expression {
this.tokens = tokens;
this.raw = !!raw;
this.flatText = !!flatText;
+ this.fuzzyFallback = !!fuzzyFallback;
}
execute(inputNoteSet: NoteSet, executionContext: {}, searchContext: SearchContext) {
@@ -238,12 +248,25 @@ class NoteContentFulltextExp extends Expression {
const { matched, negation } = this.matchesContent(content, noteId);
- if (matched) {
+ // A4: progressive phase-2 fuzzy fallback for plain-query body content. Only
+ // runs for notes that failed the cheap match above, and only when this is the
+ // default *=* content expression (fuzzyFallback) with fuzzy matching enabled.
+ const fuzzyMatched = !matched && !negation && this.fuzzyFallback && searchContext.enableFuzzyMatching
+ && this.allTokensFuzzyMatchContent(content);
+
+ if (matched || fuzzyMatched) {
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) {
+
+ if (fuzzyMatched) {
+ searchContext.recordContentMatch(noteId, {
+ tier: "fuzzy",
+ matchedTokenCount: new Set(this.tokens.flatMap((token) => tokenizeIntoWords(token))).size,
+ inOrder: false
+ });
+ } else if (!negation) {
+ // 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.
this.recordContentMatchQuality(noteId, content, searchContext);
}
}
@@ -251,6 +274,20 @@ class NoteContentFulltextExp extends Expression {
return content;
}
+ /**
+ * True when every query token fuzzy-matches (or is a substring of) some word in
+ * the content. Used only by the phase-2 fuzzy fallback; per-word work is bounded
+ * by the length-difference early-skip and AUTO edit distances.
+ */
+ private allTokensFuzzyMatchContent(content: string): boolean {
+ const normalizedContent = normalizeSearchText(content);
+
+ return this.tokens.every((token) => {
+ const normalizedToken = normalizeSearchText(token);
+ return normalizedContent.includes(normalizedToken) || this.fuzzyMatchToken(normalizedToken, normalizedContent);
+ });
+ }
+
/**
* Applies the operator's matching semantics for this note's content and
* returns whether it matched and whether the match was a negation (!=).
diff --git a/packages/trilium-core/src/services/search/services/parse.ts b/packages/trilium-core/src/services/search/services/parse.ts
index 6756c563f6..7a379dd0c8 100644
--- a/packages/trilium-core/src/services/search/services/parse.ts
+++ b/packages/trilium-core/src/services/search/services/parse.ts
@@ -56,7 +56,9 @@ function getFulltext(_tokens: TokenData[], searchContext: SearchContext, leading
const searchExpressions: Expression[] = [
new NoteFlatTextExp(tokens),
- new NoteContentFulltextExp(operator, { tokens, flatText: true }),
+ // fuzzyFallback lets progressive phase 2 fuzzy-match body content (e.g.
+ // "combinef" finding "combined"); only this default plain-query path sets it.
+ new NoteContentFulltextExp(operator, { tokens, flatText: true, fuzzyFallback: true }),
new OCRContentExpression(tokens)
];
diff --git a/packages/trilium-core/src/services/search/services/progressive_search.spec.ts b/packages/trilium-core/src/services/search/services/progressive_search.spec.ts
index 20fddba14c..6353d25978 100644
--- a/packages/trilium-core/src/services/search/services/progressive_search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/progressive_search.spec.ts
@@ -4,6 +4,8 @@ import BNote from "../../../becca/entities/bnote.js";
import BBranch from "../../../becca/entities/bbranch.js";
import SearchContext from "../search_context.js";
import becca from "../../../becca/becca.js";
+import { getContext } from "../../context.js";
+import noteService from "../../notes.js";
import { findNoteByTitle, note, NoteBuilder } from "../../../test/becca_mocking.js";
describe("Progressive Search Strategy", () => {
@@ -239,4 +241,42 @@ describe("Progressive Search Strategy", () => {
expect(searchResults.length).toBe(0);
});
});
+
+ describe("Content Match Quality Thresholds", () => {
+ function contentNote(title: string, content: string) {
+ return getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title,
+ content,
+ type: "text"
+ }).note);
+ }
+
+ it("does not run phase-2 body fuzzy matching when phase 1 has enough exact content results", () => {
+ for (let i = 0; i < 5; i++) {
+ contentNote(`Note ${i}`, `this document section ${i}`);
+ }
+ // Body typo of "document" — reachable only via the phase-2 fuzzy fallback.
+ const typo = contentNote("Typo", "this documnt section");
+
+ const searchResults = searchService.findResultsWithQuery("document", new SearchContext());
+
+ expect(searchResults.length).toBe(5);
+ expect(searchResults.some((result) => result.noteId === typo.noteId)).toBe(false);
+ });
+
+ it("counts substring-only body matches as phase-1 quality results (weight 15 clears the bar)", () => {
+ // "ument" is a substring of "document" (not an exact word or prefix), so each
+ // note earns the substring tier (15), which exceeds the quality threshold (10).
+ for (let i = 0; i < 5; i++) {
+ contentNote(`Note ${i}`, `the document ${i} here`);
+ }
+ const typo = contentNote("Typo", "the docmnt here");
+
+ const searchResults = searchService.findResultsWithQuery("ument", new SearchContext());
+
+ expect(searchResults.length).toBe(5);
+ expect(searchResults.some((result) => result.noteId === typo.noteId)).toBe(false);
+ });
+ });
});
\ No newline at end of file
diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.ts
index e990da2695..ea2ae999e9 100644
--- a/packages/trilium-core/src/services/search/services/search.spec.ts
+++ b/packages/trilium-core/src/services/search/services/search.spec.ts
@@ -809,6 +809,66 @@ describe("Search", () => {
expect(lastExactIndex).toBeLessThan(firstFuzzyIndex);
});
+ describe("content-aware ranking (search-overhaul)", () => {
+ function contentNote(title: string, content: string) {
+ return getContext().init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title,
+ content,
+ type: "text"
+ }).note);
+ }
+
+ function rank(searchResults: Array<{ noteId: string }>, noteId: string) {
+ return searchResults.findIndex((result) => result.noteId === noteId);
+ }
+
+ it("ranks a body phrase match above scattered word matches (#10616)", () => {
+ const phrase = contentNote("Alpha", "I like you and me as a phrase");
+ const scattered = contentNote("Beta", "the menu is here and you know it");
+
+ const searchResults = searchService.findResultsWithQuery("you and me", new SearchContext());
+
+ const phraseRank = rank(searchResults, phrase.noteId);
+ const scatteredRank = rank(searchResults, scattered.noteId);
+
+ expect(phraseRank).toBeGreaterThanOrEqual(0);
+ expect(scatteredRank).toBeGreaterThanOrEqual(0);
+ expect(phraseRank).toBeLessThan(scatteredRank);
+ });
+
+ it("ranks a title match above a content-only match for the same query", () => {
+ const titled = contentNote("sync stuff", "");
+ const bodyOnly = contentNote("Docs", "please sync now");
+
+ const searchResults = searchService.findResultsWithQuery("sync", new SearchContext());
+
+ const titledRank = rank(searchResults, titled.noteId);
+ const bodyRank = rank(searchResults, bodyOnly.noteId);
+
+ expect(titledRank).toBeGreaterThanOrEqual(0);
+ expect(bodyRank).toBeGreaterThanOrEqual(0);
+ expect(titledRank).toBeLessThan(bodyRank);
+ });
+
+ it("finds a body typo via phase-2 fuzzy fallback, ranked below exact matches (combinef -> combined)", () => {
+ const exact = contentNote("ExactNote", "the combinef marker is set");
+ const fuzzy = contentNote("FuzzyNote", "the values were combined together");
+
+ const searchResults = searchService.findResultsWithQuery("combinef", new SearchContext());
+
+ const exactRank = rank(searchResults, exact.noteId);
+ const fuzzyRank = rank(searchResults, fuzzy.noteId);
+
+ expect(exactRank).toBeGreaterThanOrEqual(0);
+ expect(fuzzyRank).toBeGreaterThanOrEqual(0);
+ expect(exactRank).toBeLessThan(fuzzyRank);
+ // A fuzzy-only body match (weight 5) stays below the quality threshold (10),
+ // so it never suppresses the fuzzy phase.
+ expect(searchResults[fuzzyRank].score).toBeLessThan(10);
+ });
+ });
+
// FIXME: test what happens when we order without any filter criteria