Skip to content

Build your personal knowledge base with Trilium Notes

perf(search): read only the scoped notes' content

Elian Doran6f8c8b5c0b51
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 2200546081..c38af20c33 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
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import becca from "../../../becca/becca.js";
import BBranch from "../../../becca/entities/bbranch.js";
@@ -123,6 +123,43 @@ describe("fuzzy fallback for note body content (A4)", () => {
});
});
+describe("content read from the database", () => {
+ beforeEach(() => {
+ becca.reset();
+ new NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));
+ new BBranch({ branchId: "none_root", noteId: "root", parentNoteId: "none", notePosition: 10 });
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it("reads only the notes of the input set", () => {
+ const [ inSet, outOfSet ] = [ "inside", "outside" ].map((title) => getContext().init(() =>
+ noteService.createNewNote({
+ parentNoteId: "root",
+ title,
+ content: `<p>scoped marker ${title}</p>`,
+ type: "text"
+ }).note));
+
+ const sql = getSql();
+ const iterateRows = sql.iterateRows.bind(sql);
+ const readNoteIds = new Set<string>();
+ vi.spyOn(sql, "iterateRows").mockImplementation(function* (query, params) {
+ for (const row of iterateRows<{ noteId: string }>(query, params)) {
+ readNoteIds.add(row.noteId);
+ yield row as never;
+ }
+ });
+
+ const exp = new NoteContentFulltextExp("*=*", { tokens: [ "scoped marker" ] });
+ const result = exp.execute(new NoteSet([ inSet ]), {}, new SearchContext());
+
+ expect(result.notes.map((note) => note.noteId)).toEqual([ inSet.noteId ]);
+ expect([ ...readNoteIds ]).toEqual([ inSet.noteId ]);
+ expect(readNoteIds.has(outOfSet.noteId)).toBe(false);
+ });
+});
+
describe("protected note content", () => {
beforeEach(() => {
becca.reset();
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 0e3e6e751d..e9bec280b7 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
@@ -103,13 +103,14 @@ class NoteContentFulltextExp extends Expression {
const resultNoteSet = new NoteSet();
- // Search through notes with content
+ // Search through notes with content, reading only those of `inputNoteSet`.
for (const row of getSql().iterateRows<SearchRow>(`
SELECT noteId, type, mime, content, isProtected
FROM notes JOIN blobs USING (blobId)
WHERE type IN (${SEARCHABLE_TYPES.map((type) => `'${type}'`).join(", ")})
AND isDeleted = 0
- AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}`)) {
+ AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}
+ AND noteId IN (SELECT value FROM json_each(?))`, [ inputNoteSet.toSqlParam() ])) {
this.findInText(row, inputNoteSet, resultNoteSet, searchContext);
}
diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
index 0e01a26057..64662bfb2d 100644
--- a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import becca from "../../../becca/becca.js";
import type BNote from "../../../becca/entities/bnote.js";
@@ -255,6 +255,49 @@ describe("OCRContentExpression (real DB)", () => {
expect(result.hasNote(encrypted)).toBe(true);
});
+ it("reads only the notes of the input set", () => {
+ const inSet = [
+ createNoteWithOcrText("scopedmarker own"),
+ createNoteWithOcrAttachment("scopedmarker attachment"),
+ createProtectedNoteWithOcrText("scopedmarker protected own"),
+ createProtectedNoteWithOcrAttachment("scopedmarker protected attachment")
+ ];
+ const outOfSet = [
+ createNoteWithOcrText("scopedmarker own"),
+ createNoteWithOcrAttachment("scopedmarker attachment"),
+ createProtectedNoteWithOcrText("scopedmarker protected own"),
+ createProtectedNoteWithOcrAttachment("scopedmarker protected attachment")
+ ];
+
+ const sql = getSql();
+ const getColumn = sql.getColumn.bind(sql);
+ const iterateRows = sql.iterateRows.bind(sql);
+ const readNoteIds = new Set<string>();
+ vi.spyOn(sql, "getColumn").mockImplementation((query, params) => {
+ const column = getColumn<string>(query, params);
+ for (const noteId of column) {
+ readNoteIds.add(noteId);
+ }
+ return column as never;
+ });
+ vi.spyOn(sql, "iterateRows").mockImplementation(function* (query, params) {
+ for (const row of iterateRows<{ noteId: string }>(query, params)) {
+ readNoteIds.add(row.noteId);
+ yield row as never;
+ }
+ });
+
+ const result = execute(new OCRContentExpression([ "scopedmarker" ]), new NoteSet(inSet));
+ vi.restoreAllMocks();
+
+ const inSetIds = inSet.map((note) => note.noteId).sort();
+ expect(noteIds(result)).toEqual(inSetIds);
+ expect([ ...readNoteIds ].sort()).toEqual(inSetIds);
+ for (const note of outOfSet) {
+ expect(readNoteIds.has(note.noteId)).toBe(false);
+ }
+ });
+
it("cannot match a protected note once the session is closed", () => {
const note = createProtectedNoteWithOcrText("Protected passport number");
diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.ts
index de826d7696..1468140694 100644
--- a/packages/trilium-core/src/services/search/expressions/ocr_content.ts
+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.ts
@@ -25,7 +25,7 @@ export default class OCRContentExpression extends Expression {
execute(inputNoteSet: NoteSet, executionContext: object, searchContext: SearchContext): NoteSet {
const resultNoteSet = new NoteSet();
- const matchingNoteIds = this.findNoteIdsWithMatchingOCR();
+ const matchingNoteIds = this.findNoteIdsWithMatchingOCR(inputNoteSet);
for (const noteId of matchingNoteIds) {
const note = becca.notes[noteId];
@@ -45,24 +45,24 @@ export default class OCRContentExpression extends Expression {
}
/**
- * Find all noteIds that have OCR text matching all tokens.
+ * Find the noteIds of `inputNoteSet` that have OCR text matching all tokens.
* Checks both the note's own blob and its attachment blobs.
*/
- private findNoteIdsWithMatchingOCR(): Set<string> {
+ private findNoteIdsWithMatchingOCR(inputNoteSet: NoteSet): Set<string> {
if (this.tokens.length === 0) return new Set();
const matchingNoteIds = new Set<string>();
- this.collectUnprotectedMatches(matchingNoteIds);
- this.collectProtectedMatches(matchingNoteIds);
+ this.collectUnprotectedMatches(inputNoteSet, matchingNoteIds);
+ this.collectProtectedMatches(inputNoteSet, matchingNoteIds);
return matchingNoteIds;
}
/** The stored text is the readable text, so all tokens must appear in it. */
- private collectUnprotectedMatches(matchingNoteIds: Set<string>) {
+ private collectUnprotectedMatches(inputNoteSet: NoteSet, matchingNoteIds: Set<string>) {
const likeConditions = this.tokens.map(() => `b.textRepresentation LIKE ?`).join(' AND ');
- const params = this.tokens.map(token => `%${token}%`);
+ const params = [ ...this.tokens.map(token => `%${token}%`), inputNoteSet.toSqlParam() ];
const sql = getSql();
// Notes whose own blob matches.
@@ -74,6 +74,7 @@ export default class OCRContentExpression extends Expression {
AND n.isDeleted = 0
AND n.isProtected = 0
AND ${likeConditions}
+ AND n.noteId IN (SELECT value FROM json_each(?))
`, params);
// Notes that own an attachment whose blob matches.
@@ -85,6 +86,7 @@ export default class OCRContentExpression extends Expression {
AND a.isDeleted = 0
AND a.isProtected = 0
AND ${likeConditions}
+ AND a.ownerId IN (SELECT value FROM json_each(?))
`, params);
for (const noteId of [...noteIds, ...attachmentOwnerIds]) {
@@ -99,7 +101,7 @@ export default class OCRContentExpression extends Expression {
* rather than the file itself, so this stays far smaller than the note-content search that
* already works this way.
*/
- private collectProtectedMatches(matchingNoteIds: Set<string>) {
+ private collectProtectedMatches(inputNoteSet: NoteSet, matchingNoteIds: Set<string>) {
if (!protectedSessionService.isProtectedSessionAvailable()) {
return;
}
@@ -112,18 +114,21 @@ export default class OCRContentExpression extends Expression {
JOIN blobs b ON n.blobId = b.blobId
WHERE b.textRepresentation IS NOT NULL
AND n.isDeleted = 0
- AND n.isProtected = 1`,
+ AND n.isProtected = 1
+ AND n.noteId IN (SELECT value FROM json_each(?))`,
/*sql*/`
SELECT a.ownerId AS noteId, b.textRepresentation AS textRepresentation
FROM attachments a
JOIN blobs b ON a.blobId = b.blobId
WHERE b.textRepresentation IS NOT NULL
AND a.isDeleted = 0
- AND a.isProtected = 1`
+ AND a.isProtected = 1
+ AND a.ownerId IN (SELECT value FROM json_each(?))`
];
+ const params = [ inputNoteSet.toSqlParam() ];
for (const query of queries) {
- for (const row of sql.iterateRows<{ noteId: string; textRepresentation: string }>(query)) {
+ for (const row of sql.iterateRows<{ noteId: string; textRepresentation: string }>(query, params)) {
if (matchingNoteIds.has(row.noteId)) {
continue;
}
diff --git a/packages/trilium-core/src/services/search/note_set.ts b/packages/trilium-core/src/services/search/note_set.ts
index c621017786..de80bdce4f 100644
--- a/packages/trilium-core/src/services/search/note_set.ts
+++ b/packages/trilium-core/src/services/search/note_set.ts
@@ -33,6 +33,11 @@ class NoteSet {
return this.noteIdSet.has(noteId);
}
+ /** The note IDs as one JSON array, the parameter of `IN (SELECT value FROM json_each(?))`. */
+ toSqlParam() {
+ return JSON.stringify([ ...this.noteIdSet ]);
+ }
+
mergeIn(anotherNoteSet: NoteSet) {
this.addAll(anotherNoteSet.notes);
}