Skip to content

Build your personal knowledge base with Trilium Notes

perf(search): optimize scoring, highlighting, and tree walk

perfectra1nac231374f69d
diff --git a/apps/server/src/services/search/expressions/note_flat_text.ts b/apps/server/src/services/search/expressions/note_flat_text.ts
index ef3efbf66f..b12413738e 100644
--- a/apps/server/src/services/search/expressions/note_flat_text.ts
+++ b/apps/server/src/services/search/expressions/note_flat_text.ts
@@ -23,6 +23,18 @@ class NoteFlatTextExp extends Expression {
execute(inputNoteSet: NoteSet, executionContext: any, searchContext: SearchContext) {
const resultNoteSet = new NoteSet();
+ // Cache normalized titles to avoid redundant normalize+getNoteTitle calls
+ const titleCache = new Map<string, string>();
+ const getNormalizedTitle = (noteId: string, parentNoteId: string): string => {
+ const key = `${noteId}-${parentNoteId}`;
+ let cached = titleCache.get(key);
+ if (cached === undefined) {
+ cached = normalizeSearchText(beccaService.getNoteTitle(noteId, parentNoteId));
+ titleCache.set(key, cached);
+ }
+ return cached;
+ };
+
/**
* @param note
* @param remainingTokens - tokens still needed to be found in the path towards root
@@ -38,10 +50,8 @@ class NoteFlatTextExp extends Expression {
const noteId = resultPath[resultPath.length - 1];
if (!resultNoteSet.hasNoteId(noteId)) {
- // we could get here from multiple paths, the first one wins because the paths
- // are sorted by importance
+ // Snapshot takenPath since it's mutable
executionContext.noteIdToNotePath[noteId] = resultPath;
-
resultNoteSet.add(becca.notes[noteId]);
}
}
@@ -50,18 +60,14 @@ class NoteFlatTextExp extends Expression {
}
if (note.parents.length === 0 || note.noteId === "root") {
- // we've reached root, but there are still remaining tokens -> this candidate note produced no result
return;
}
const foundAttrTokens: string[] = [];
for (const token of remainingTokens) {
- // Add defensive checks for undefined properties
- const typeMatches = note.type && note.type.includes(token);
- const mimeMatches = note.mime && note.mime.includes(token);
-
- if (typeMatches || mimeMatches) {
+ if ((note.type && note.type.includes(token)) ||
+ (note.mime && note.mime.includes(token))) {
foundAttrTokens.push(token);
}
}
@@ -75,17 +81,19 @@ class NoteFlatTextExp extends Expression {
}
for (const parentNote of note.parents) {
- const title = normalizeSearchText(beccaService.getNoteTitle(note.noteId, parentNote.noteId));
- const foundTokens: string[] = foundAttrTokens.slice();
+ const title = getNormalizedTitle(note.noteId, parentNote.noteId);
+
+ // Use Set for O(1) lookup instead of Array.includes() which is O(n)
+ const foundTokenSet = new Set<string>(foundAttrTokens);
for (const token of remainingTokens) {
if (this.smartMatch(title, token, searchContext)) {
- foundTokens.push(token);
+ foundTokenSet.add(token);
}
}
- if (foundTokens.length > 0) {
- const newRemainingTokens = remainingTokens.filter((token) => !foundTokens.includes(token));
+ if (foundTokenSet.size > 0) {
+ const newRemainingTokens = remainingTokens.filter((token) => !foundTokenSet.has(token));
searchPathTowardsRoot(parentNote, newRemainingTokens, [note.noteId, ...takenPath]);
} else {
diff --git a/apps/server/src/services/search/search_result.ts b/apps/server/src/services/search/search_result.ts
index bf8a33524b..57e2417cf7 100644
--- a/apps/server/src/services/search/search_result.ts
+++ b/apps/server/src/services/search/search_result.ts
@@ -59,8 +59,9 @@ class SearchResult {
this.fuzzyScore = 0; // Reset fuzzy score tracking
const note = becca.notes[this.noteId];
- const normalizedQuery = normalizeSearchText(fulltextQuery.toLowerCase());
- const normalizedTitle = normalizeSearchText(note.title.toLowerCase());
+ // normalizeSearchText already lowercases — no need for .toLowerCase() first
+ const normalizedQuery = normalizeSearchText(fulltextQuery);
+ const normalizedTitle = normalizeSearchText(note.title);
// Note ID exact match, much higher score
if (note.noteId.toLowerCase() === fulltextQuery) {
@@ -91,35 +92,37 @@ class SearchResult {
}
addScoreForStrings(tokens: string[], str: string, factor: number, enableFuzzyMatching: boolean = true) {
- const normalizedStr = normalizeSearchText(str.toLowerCase());
+ // normalizeSearchText already lowercases — no need for .toLowerCase() first
+ const normalizedStr = normalizeSearchText(str);
const chunks = normalizedStr.split(" ");
+ // Pre-normalize tokens once instead of per-chunk
+ const normalizedTokens = tokens.map(t => normalizeSearchText(t));
+
let tokenScore = 0;
for (const chunk of chunks) {
- for (const token of tokens) {
- const normalizedToken = normalizeSearchText(token.toLowerCase());
-
+ for (let ti = 0; ti < normalizedTokens.length; ti++) {
+ const normalizedToken = normalizedTokens[ti];
+
if (chunk === normalizedToken) {
- tokenScore += SCORE_WEIGHTS.TOKEN_EXACT_MATCH * token.length * factor;
+ tokenScore += SCORE_WEIGHTS.TOKEN_EXACT_MATCH * tokens[ti].length * factor;
} else if (chunk.startsWith(normalizedToken)) {
- tokenScore += SCORE_WEIGHTS.TOKEN_PREFIX_MATCH * token.length * factor;
+ tokenScore += SCORE_WEIGHTS.TOKEN_PREFIX_MATCH * tokens[ti].length * factor;
} else if (chunk.includes(normalizedToken)) {
- tokenScore += SCORE_WEIGHTS.TOKEN_CONTAINS_MATCH * token.length * factor;
- } else {
- // Try fuzzy matching for individual tokens with caps applied
+ tokenScore += SCORE_WEIGHTS.TOKEN_CONTAINS_MATCH * tokens[ti].length * factor;
+ } 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 &&
- normalizedToken.length >= FUZZY_SEARCH_CONFIG.MIN_FUZZY_TOKEN_LENGTH &&
- this.fuzzyScore < SCORE_WEIGHTS.MAX_TOTAL_FUZZY_SCORE) {
-
+ if (editDistance <= FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE) {
const fuzzyWeight = SCORE_WEIGHTS.TOKEN_FUZZY_MATCH * (1 - editDistance / FUZZY_SEARCH_CONFIG.MAX_EDIT_DISTANCE);
- // Apply caps: limit token length multiplier and per-token contribution
- const cappedTokenLength = Math.min(token.length, SCORE_WEIGHTS.MAX_FUZZY_TOKEN_LENGTH_MULTIPLIER);
+ const cappedTokenLength = Math.min(tokens[ti].length, SCORE_WEIGHTS.MAX_FUZZY_TOKEN_LENGTH_MULTIPLIER);
const fuzzyTokenScore = Math.min(
fuzzyWeight * cappedTokenLength * factor,
SCORE_WEIGHTS.MAX_FUZZY_SCORE_PER_TOKEN
);
-
+
tokenScore += fuzzyTokenScore;
this.fuzzyScore += fuzzyTokenScore;
}
diff --git a/apps/server/src/services/search/services/search.ts b/apps/server/src/services/search/services/search.ts
index b533c185fe..49eb6d0d71 100644
--- a/apps/server/src/services/search/services/search.ts
+++ b/apps/server/src/services/search/services/search.ts
@@ -722,37 +722,40 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens
}
for (const result of searchResults) {
- // Reset token
- const tokenRegex = new RegExp(escapeRegExp(token), "gi");
let match;
// Highlight in note path title
if (result.highlightedNotePathTitle) {
const titleRegex = new RegExp(escapeRegExp(token), "gi");
- while ((match = titleRegex.exec(removeDiacritic(result.highlightedNotePathTitle))) !== null) {
+ // Compute diacritic-free version ONCE before the loop, not on every iteration
+ let titleNoDiacritics = removeDiacritic(result.highlightedNotePathTitle);
+ while ((match = titleRegex.exec(titleNoDiacritics)) !== null) {
result.highlightedNotePathTitle = wrapText(result.highlightedNotePathTitle, match.index, token.length, "{", "}");
- // 2 characters are added, so we need to adjust the index
+ // 2 characters are added, so we need to adjust the index and re-derive
titleRegex.lastIndex += 2;
+ titleNoDiacritics = removeDiacritic(result.highlightedNotePathTitle);
}
}
// Highlight in content snippet
if (result.highlightedContentSnippet) {
const contentRegex = new RegExp(escapeRegExp(token), "gi");
- while ((match = contentRegex.exec(removeDiacritic(result.highlightedContentSnippet))) !== null) {
+ let contentNoDiacritics = removeDiacritic(result.highlightedContentSnippet);
+ while ((match = contentRegex.exec(contentNoDiacritics)) !== null) {
result.highlightedContentSnippet = wrapText(result.highlightedContentSnippet, match.index, token.length, "{", "}");
- // 2 characters are added, so we need to adjust the index
contentRegex.lastIndex += 2;
+ contentNoDiacritics = removeDiacritic(result.highlightedContentSnippet);
}
}
// Highlight in attribute snippet
if (result.highlightedAttributeSnippet) {
const attributeRegex = new RegExp(escapeRegExp(token), "gi");
- while ((match = attributeRegex.exec(removeDiacritic(result.highlightedAttributeSnippet))) !== null) {
+ let attrNoDiacritics = removeDiacritic(result.highlightedAttributeSnippet);
+ while ((match = attributeRegex.exec(attrNoDiacritics)) !== null) {
result.highlightedAttributeSnippet = wrapText(result.highlightedAttributeSnippet, match.index, token.length, "{", "}");
- // 2 characters are added, so we need to adjust the index
attributeRegex.lastIndex += 2;
+ attrNoDiacritics = removeDiacritic(result.highlightedAttributeSnippet);
}
}
}
diff --git a/apps/server/src/services/search/utils/text_utils.ts b/apps/server/src/services/search/utils/text_utils.ts
index 9274241cbc..94df2f3dd1 100644
--- a/apps/server/src/services/search/utils/text_utils.ts
+++ b/apps/server/src/services/search/utils/text_utils.ts
@@ -275,21 +275,19 @@ export function fuzzyMatchWordWithResult(token: string, text: string, maxDistanc
}
try {
- // Normalize both strings for comparison
- const normalizedToken = token.toLowerCase();
- const normalizedText = text.toLowerCase();
-
+ // Inputs from smartMatch() are already normalized (lowercased, diacritics removed).
+ // Skip redundant toLowerCase() — just use the inputs directly.
+
// Exact match check first (most common case)
- if (normalizedText.includes(normalizedToken)) {
- // Find the exact match in the original text to preserve case
- const exactMatch = text.match(new RegExp(escapeRegExp(token), 'i'));
- return exactMatch ? exactMatch[0] : token;
+ if (text.includes(token)) {
+ return token;
}
-
- // For fuzzy matching, we need to check individual words in the text
- // Split the text into words and check each word against the token
- const words = normalizedText.split(/\s+/).filter(word => word.length > 0);
- const originalWords = text.split(/\s+/).filter(word => word.length > 0);
+
+ // For fuzzy matching, we need to check individual words in the text.
+ // Split into words and check each word against the token.
+ // Inputs are already normalized so we don't need a separate originalWords array.
+ const words = text.split(/\s+/);
+ const originalWords = words;
for (let i = 0; i < words.length; i++) {
const word = words[i];