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): length-scaled fuzzy edit distance (#10616)
perfectra1n5d2f6b2c0aff
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 1b81a0b32b..52e5368f03 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@@ -8,6 +8,7 @@ import type SearchContext from "../search_context.js";import {FUZZY_SEARCH_CONFIG,fuzzyMatchWord,+ getAutoMaxEditDistance,normalizeSearchText,stripWordPunctuation,tokenizeIntoWords,@@ -437,8 +438,9 @@ class NoteContentFulltextExp extends Expression {* Fuzzy matches a single token against a single word*/private fuzzyMatchSingle(token: string, word: string): boolean {- // Use shared optimized fuzzy matching logic- return fuzzyMatchWord(token, word, FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE);+ // Use shared optimized fuzzy matching logic with a length-scaled (AUTO)+ // edit-distance bound so short tokens don't produce false positives.+ return fuzzyMatchWord(token, word, getAutoMaxEditDistance(token.length));}}diff --git a/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.ts b/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.tsindex 3becc3ee60..61ea206c52 100644--- a/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.ts+++ b/packages/trilium-core/src/services/search/expressions/note_flat_text.spec.ts@@ -186,6 +186,17 @@ describe("NoteFlatTextExp", () => {expect(ctx.highlightedTokens).toContain("austria");});+ it("does not fuzzy-match a short token at edit distance 2 (sync !~ Send, #10616)", () => {+ // "sync" (4 chars) is edit distance 2 from "send"; under length-scaled+ // fuzzy matching a 4-char token only tolerates a single edit, so the+ // title "Send" must NOT be matched by the token "sync".+ const send = note("Send");+ rootNote.child(send);++ const ctx = searchContext({ enableFuzzyMatching: true });+ expect(execute(new NoteFlatTextExp(["sync"]), ctx).result.notes).toHaveLength(0);+ });+describe("getNotePath", () => {it("throws when the taken path is empty", () => {const austria = note("Austria");diff --git a/packages/trilium-core/src/services/search/expressions/note_flat_text.ts b/packages/trilium-core/src/services/search/expressions/note_flat_text.tsindex 17beffb721..1d76a1e9db 100644--- a/packages/trilium-core/src/services/search/expressions/note_flat_text.ts+++ b/packages/trilium-core/src/services/search/expressions/note_flat_text.ts@@ -3,7 +3,7 @@ import becca from "../../../becca/becca.js";import type BNote from "../../../becca/entities/bnote.js";import NoteSet from "../note_set.js";import type SearchContext from "../search_context.js";-import { fuzzyMatchWordWithResult, normalizeSearchText } from "../utils/text_utils.js";+import { fuzzyMatchWordWithResult, getAutoMaxEditDistance, normalizeSearchText } from "../utils/text_utils.js";import Expression from "./expression.js";class NoteFlatTextExp extends Expression {@@ -226,8 +226,9 @@ class NoteFlatTextExp extends Expression {return true;}- // Fuzzy fallback only if enabled and for tokens >= 4 characters- if (searchContext?.enableFuzzyMatching && token.length >= 4) {+ // Fuzzy fallback only if enabled and the token is long enough to allow any+ // edit distance under the length-scaled (AUTO) rule (i.e. >= 3 characters).+ if (searchContext?.enableFuzzyMatching && getAutoMaxEditDistance(token.length) > 0) {const matchedWord = fuzzyMatchWordWithResult(token, text);if (matchedWord) {// Track the fuzzy matched word for highlightingdiff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.tsindex c66489035c..3f16ef3da5 100644--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@ -3,6 +3,7 @@ import becca_service from "../../becca/becca_service.js";import {calculateOptimizedEditDistance,FUZZY_SEARCH_CONFIG,+ getAutoMaxEditDistance,normalizeSearchText,stripWordPunctuation,tokenizeIntoWords,@@ -116,9 +117,12 @@ class SearchResult {} else if (enableFuzzyMatching &&normalizedToken.length >= FUZZY_SEARCH_CONFIG.MIN_FUZZY_TOKEN_LENGTH &&this.fuzzyScore < SCORE_WEIGHTS.MAX_TOTAL_FUZZY_SCORE) {- // Only compute edit distance when fuzzy matching is enabled- const editDistance = calculateOptimizedEditDistance(chunk, normalizedToken, FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE);- if (editDistance <= FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE) {+ // Only compute edit distance when fuzzy matching is enabled.+ // Cap the per-chunk distance with the length-scaled (AUTO) bound+ // so short tokens can't fuzzy-match at distance 2.+ const maxEditDistance = getAutoMaxEditDistance(normalizedToken.length);+ const editDistance = calculateOptimizedEditDistance(chunk, normalizedToken, maxEditDistance);+ if (editDistance <= maxEditDistance) {const fuzzyWeight = SCORE_WEIGHTS.TOKEN_FUZZY_MATCH * (1 - editDistance / FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE);const cappedTokenLength = Math.min(tokens[ti].length, SCORE_WEIGHTS.MAX_FUZZY_TOKEN_LENGTH_MULTIPLIER);const fuzzyTokenScore = Math.min(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.tsindex 6bf6c23793..20fddba14c 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@@ -117,19 +117,19 @@ describe("Progressive Search Strategy", () => {it("should not duplicate results between phases", () => {rootNote- .child(note("Test Document")) // Would match in both phases- .child(note("Tset Report")); // Only fuzzy match+ .child(note("Test Document")) // exact match on "document"+ .child(note("Reference Documnt")); // fuzzy match on "document" (typo)const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery("test", searchContext);+ const searchResults = searchService.findResultsWithQuery("document", searchContext);// Should only have unique resultsconst noteIds = searchResults.map(r => r.noteId);const uniqueNoteIds = [...new Set(noteIds)];-+expect(noteIds.length).toBe(uniqueNoteIds.length);expect(findNoteByTitle(searchResults, "Test Document")).toBeTruthy();- expect(findNoteByTitle(searchResults, "Tset Report")).toBeTruthy();+ expect(findNoteByTitle(searchResults, "Reference Documnt")).toBeTruthy();});});@@ -137,31 +137,31 @@ describe("Progressive Search Strategy", () => {it("should respect minimum result count threshold", () => {// Create exactly 4 high-quality results (below threshold of 5)rootNote- .child(note("Test One"))- .child(note("Test Two"))- .child(note("Test Three"))- .child(note("Test Four"))- .child(note("Tset Five")); // Typo that should be found via fuzzy+ .child(note("Document One"))+ .child(note("Document Two"))+ .child(note("Document Three"))+ .child(note("Document Four"))+ .child(note("Documnt Five")); // Typo that should be found via fuzzyconst searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery("test", searchContext);+ const searchResults = searchService.findResultsWithQuery("document", searchContext);// Should proceed to Phase 2 and include fuzzy matchexpect(searchResults.length).toBe(5);- expect(findNoteByTitle(searchResults, "Tset Five")).toBeTruthy();+ expect(findNoteByTitle(searchResults, "Documnt Five")).toBeTruthy();});it("should respect minimum quality score threshold", () => {// Create notes that might have low exact match scoresrootNote.child(note("Testing Document")) // Should have decent score- .child(note("Document with test inside")) // Lower score due to position- .child(note("Another test case"))- .child(note("Test case example"))- .child(note("Tset with typo")); // Fuzzy match+ .child(note("Reference to a document")) // Lower score due to position+ .child(note("Another documentation")) // contains "document" as a substring+ .child(note("Document example"))+ .child(note("Reference Documnt")); // Fuzzy matchconst searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery("test", searchContext);+ const searchResults = searchService.findResultsWithQuery("document", searchContext);// Should include fuzzy results if exact results don't meet quality thresholdexpect(searchResults.length).toBeGreaterThan(4);@@ -192,11 +192,12 @@ describe("Progressive Search Strategy", () => {});it("should enforce maximum total fuzzy score per search", () => {- // Create note with many potential fuzzy matches- rootNote.child(note("Tset Documnt Anaylsis Sumary Reportng")); // Many typos+ // Create note with many potential fuzzy matches (all 6+ chars so they+ // still fuzzy-match under length-scaled distance)+ rootNote.child(note("Documnt Anaylsis Sumary Reportng")); // Many typosconst searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery("test document analysis summary reporting", searchContext);+ const searchResults = searchService.findResultsWithQuery("document analysis summary reporting", searchContext);expect(searchResults.length).toBe(1);@@ -209,22 +210,22 @@ describe("Progressive Search Strategy", () => {it("should respect enableFuzzyMatching flag", () => {rootNote.child(note("Test Document"))- .child(note("Tset Report")); // Typo+ .child(note("Reference Documnt")); // Typo// Test with fuzzy matching disabledconst exactOnlyContext = new SearchContext();exactOnlyContext.enableFuzzyMatching = false;-- const exactResults = searchService.findResultsWithQuery("test", exactOnlyContext);++ const exactResults = searchService.findResultsWithQuery("document", exactOnlyContext);expect(exactResults.length).toBe(1);expect(findNoteByTitle(exactResults, "Test Document")).toBeTruthy();- expect(findNoteByTitle(exactResults, "Tset Report")).toBeFalsy();+ expect(findNoteByTitle(exactResults, "Reference Documnt")).toBeFalsy();// Test with fuzzy matching enabled (default)const fuzzyContext = new SearchContext();- const fuzzyResults = searchService.findResultsWithQuery("test", fuzzyContext);+ const fuzzyResults = searchService.findResultsWithQuery("document", fuzzyContext);expect(fuzzyResults.length).toBe(2);- expect(findNoteByTitle(fuzzyResults, "Tset Report")).toBeTruthy();+ expect(findNoteByTitle(fuzzyResults, "Reference Documnt")).toBeTruthy();});});diff --git a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts b/packages/trilium-core/src/services/search/utils/text_utils.spec.tsindex cfb5b8c85e..9d55518181 100644--- a/packages/trilium-core/src/services/search/utils/text_utils.spec.ts+++ b/packages/trilium-core/src/services/search/utils/text_utils.spec.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, stripHtmlTags, stripWordPunctuation, tokenizeIntoWords, wordsContainPhrase } from './text_utils.js';+import { calculateOptimizedEditDistance, validateFuzzySearchTokens, fuzzyMatchWord, fuzzyMatchWordWithResult, getAutoMaxEditDistance, stripHtmlTags, stripWordPunctuation, tokenizeIntoWords, wordsContainPhrase } from './text_utils.js';describe('Fuzzy Search Core', () => {describe('calculateOptimizedEditDistance', () => {@@ -49,10 +49,14 @@ describe('Fuzzy Search Core', () => {expect(fuzzyMatchWord('naive', 'naïve')).toBe(true);});- it('matches with typos within distance threshold', () => {+ it('matches with typos within the length-scaled distance threshold', () => {+ // helo -> hello is a single edit (d=1), allowed for 5-char tokens.expect(fuzzyMatchWord('hello', 'helo')).toBe(true);- expect(fuzzyMatchWord('world', 'wrold')).toBe(true);- expect(fuzzyMatchWord('test', 'tset')).toBe(true);+ // wrold/tset are transpositions (Levenshtein d=2). Under length-scaled+ // distance, <=5-char tokens only allow d=1, so these no longer match.+ // (Old behavior allowed a flat d=2 for any length — too loose, #10616.)+ expect(fuzzyMatchWord('world', 'wrold')).toBe(false);+ expect(fuzzyMatchWord('test', 'tset')).toBe(false);expect(fuzzyMatchWord('test', 'xyz')).toBe(false);});@@ -107,6 +111,44 @@ describe('Fuzzy Search Core', () => {});});+ describe('getAutoMaxEditDistance', () => {+ it('scales the allowed edit distance by token length (Elasticsearch AUTO-style)', () => {+ // 0-2 chars: no fuzzy.+ expect(getAutoMaxEditDistance(0)).toBe(0);+ expect(getAutoMaxEditDistance(1)).toBe(0);+ expect(getAutoMaxEditDistance(2)).toBe(0);+ // 3-5 chars: 1 edit.+ expect(getAutoMaxEditDistance(3)).toBe(1);+ expect(getAutoMaxEditDistance(4)).toBe(1);+ expect(getAutoMaxEditDistance(5)).toBe(1);+ // 6+ chars: 2 edits.+ expect(getAutoMaxEditDistance(6)).toBe(2);+ expect(getAutoMaxEditDistance(8)).toBe(2);+ expect(getAutoMaxEditDistance(20)).toBe(2);+ });++ it('rejects distance-2 typos for short (<=5 char) tokens', () => {+ // "sync" (4) vs "send": d=2 > 1 -> no fuzzy match (was a false positive).+ expect(fuzzyMatchWord('sync', 'send')).toBe(false);+ // "ceck" (4) vs "tech": d=2 > 1 -> no fuzzy match.+ expect(fuzzyMatchWord('ceck', 'tech')).toBe(false);+ });++ it('allows distance-2 typos for longer (6+ char) tokens', () => {+ // "combinef" (8) vs "combined": d=1 <= 2 -> fuzzy match.+ expect(fuzzyMatchWord('combinef', 'combined')).toBe(true);+ });++ it('does not treat a substring word as a fuzzy match', () => {+ // "sync" is a substring of "async"; substring semantics belong to the+ // callers' own .includes() checks, not to the fuzzy matcher. So the+ // fuzzy matcher alone reports no match here.+ expect(fuzzyMatchWordWithResult('sync', 'async text')).toBeNull();+ // Sanity: a genuine 1-edit typo of a 4-char token still matches.+ expect(fuzzyMatchWordWithResult('sync', 'sinc')).toBe('sinc');+ });+ });+describe('wordsContainPhrase', () => {it('matches a consecutive run of words in order', () => {expect(wordsContainPhrase(['a', 'exact', 'phrase', 'b'], ['exact', 'phrase'])).toBe(true);diff --git a/packages/trilium-core/src/services/search/utils/text_utils.ts b/packages/trilium-core/src/services/search/utils/text_utils.tsindex 7e39f4093a..048b71883d 100644--- a/packages/trilium-core/src/services/search/utils/text_utils.ts+++ b/packages/trilium-core/src/services/search/utils/text_utils.ts@@ -279,6 +279,31 @@ function escapeRegExp(string: string): string {return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}+/**+ * Returns the maximum edit distance allowed for a fuzzy match of a token of the+ * given length, scaled by length in the style of Elasticsearch's `fuzziness:+ * AUTO`. A flat edit distance of 2 is too loose for short words (e.g. "sync"+ * would match "send"), so short tokens get a tighter bound.+ *+ * - 0-2 chars: 0 (no fuzzy matching)+ * - 3-5 chars: 1+ * - 6+ chars: 2+ *+ * The result never exceeds {@link FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE}.+ *+ * @param tokenLength The length of the token being matched.+ * @returns The maximum allowed edit distance for that token.+ */+export function getAutoMaxEditDistance(tokenLength: number): number {+ if (tokenLength <= 2) {+ return 0;+ }+ if (tokenLength <= 5) {+ return 1;+ }+ return FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE;+}+/*** Checks if a word matches a token with fuzzy matching and returns the matched word.* Optimized for common case where distances are small.@@ -288,7 +313,7 @@ function escapeRegExp(string: string): string {* @param maxDistance Maximum allowed edit distance* @returns The matched word if found, null otherwise*/-export function fuzzyMatchWordWithResult(token: string, text: string, maxDistance: number = FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE): string | null {+export function fuzzyMatchWordWithResult(token: string, text: string, maxDistance: number = getAutoMaxEditDistance(token.length)): string | null {// Input validationif (typeof token !== 'string' || typeof text !== 'string') {return null;@@ -304,12 +329,11 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistancconst normalizedToken = token.toLowerCase();const normalizedText = text.toLowerCase();- // Exact match check first (most common case)- if (normalizedText.includes(normalizedToken)) {- // Find the exact match position and return the original substring with case preserved- const matchIndex = normalizedText.indexOf(normalizedToken);- return text.substring(matchIndex, matchIndex + normalizedToken.length);- }+ // NOTE: no whole-text substring shortcut here. Substring relationships are+ // NOT fuzzy matches — callers that want substring semantics do their own+ // .includes() check first (note_flat_text smartMatch, build_comparator ~=,+ // note_content_fulltext tokenMatchesContent). Letting "async" count as a+ // fuzzy match for "sync" was a false positive (#10616).// For fuzzy matching, split into words and check each against the tokenconst words = normalizedText.split(/\s+/).filter(word => word.length > 0);@@ -319,17 +343,20 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistancconst word = words[i];const originalWord = originalWords[i];- // Skip if word is too different in length for fuzzy matching- if (Math.abs(word.length - normalizedToken.length) > maxDistance) {+ // A word that literally contains the token is a substring relationship,+ // not a fuzzy (typo) one — skip it so e.g. "sync" does not fuzzy-match+ // "async". Callers handle substrings via their own .includes() checks.+ if (word.length > normalizedToken.length && word.includes(normalizedToken)) {continue;}- // For very short tokens or very different lengths, be more strict- if (normalizedToken.length < 4 || Math.abs(word.length - normalizedToken.length) > 2) {+ // Skip if word is too different in length for fuzzy matching+ if (Math.abs(word.length - normalizedToken.length) > maxDistance) {continue;}- // Use optimized edit distance calculation+ // Use optimized edit distance calculation. maxDistance is length-scaled+ // (Elasticsearch AUTO-style) via getAutoMaxEditDistance by default.const distance = calculateOptimizedEditDistance(normalizedToken, word, maxDistance);if (distance <= maxDistance) {return originalWord; // Return the original word with case preserved@@ -353,7 +380,7 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc* @param maxDistance Maximum allowed edit distance* @returns True if the word matches the token within the distance threshold*/-export function fuzzyMatchWord(token: string, text: string, maxDistance: number = FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE): boolean {+export function fuzzyMatchWord(token: string, text: string, maxDistance: number = getAutoMaxEditDistance(token.length)): boolean {return fuzzyMatchWordWithResult(token, text, maxDistance) !== null;}