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): follow links and backlinks with note.links and note.backlinks
Elian Doran07b9284fc4f4
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ff9671e8f7..348d39e613 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4535,6 +4535,8 @@"property_parents": "Continues on the note's parents","property_children": "Continues on the note's children","property_ancestors": "Continues on the note's ancestors",+ "property_links": "Continues on the notes this note links to",+ "property_backlinks": "Continues on the notes linking to this note","property_labels": "Followed by a label name","property_relations": "Followed by a relation name, then that note's own properties","property_attribute_count": "Number of labels and relations, including inherited ones",diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.tsindex 0e57af207c..23745945cd 100644--- a/apps/client/src/widgets/ribbon/search_completions.ts+++ b/apps/client/src/widgets/ribbon/search_completions.ts@@ -480,6 +480,8 @@ const SEGMENTS: Record<NotePathSegment, { icon: string; detail?: string }> = {parents: { icon: "bx-up-arrow-alt", detail: "search_completion.property_parents" },children: { icon: "bx-sitemap", detail: "search_completion.property_children" },ancestors: { icon: "bx-git-branch", detail: "search_completion.property_ancestors" },+ links: { icon: "bx-link", detail: "search_completion.property_links" },+ backlinks: { icon: "bx-link-alt", detail: "search_completion.property_backlinks" },labels: { icon: "bx-hash", detail: "search_completion.property_labels" },relations: { icon: "bx-transfer", detail: "search_completion.property_relations" }};diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.htmlindex a4989e1282..5b9d9444d8 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html@@ -338,6 +338,16 @@named "Books".</li><li><code>note.children.title = 'sub-note'</code>: Find notes with a childnamed "sub-note".</li>+ <li><code>note.links.title = 'Tolkien'</code>: Find notes linking to a note+ named "Tolkien", the same notes its <a class="reference-link" href="#root/_help_wfGXLmm7x27z">Backlinks</a> list.</li>+ <li><code>note.backlinks.title = 'Reading list'</code>: Find the notes that+ "Reading list" links to.</li>+ <li>A link is a relation you created, such as <code>~author</code>, or one+ that content creates: an internal link (<code>~internalLink</code>), an+ image (<code>~imageLink</code>), an included note (<code>~includeNoteLink</code>)+ or a relation map connection (<code>~relationMapLink</code>). Relations+ that configure a note, such as <code>~template</code> or a saved search's <code>~ancestor</code>,+ are not links.</li></ul><p>See also <a class="reference-link" href="#root/_help_Oxyb6jOjjVNL">Under the hood</a> formore syntax references.</p>diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.mdindex 6c8eb6276f..097ffec6be 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md@@ -172,6 +172,9 @@ In addition:* `note.parents.parents.title = 'Books'`: Find notes with a grandparent named "Books".* `note.ancestors.title = 'Books'`: Find notes with an ancestor named "Books".* `note.children.title = 'sub-note'`: Find notes with a child named "sub-note".+* `note.links.title = 'Tolkien'`: Find notes linking to a note named "Tolkien", the same notes its <a class="reference-link" href="../../Note%20Types/Text/Links/Backlinks.md">Backlinks</a> list.+* `note.backlinks.title = 'Reading list'`: Find the notes that "Reading list" links to.+* A link is a relation you created, such as `~author`, or one that content creates: an internal link (`~internalLink`), an image (`~imageLink`), an included note (`~includeNoteLink`) or a relation map connection (`~relationMapLink`). Relations that configure a note, such as `~template` or a saved search's `~ancestor`, are not links.See also <a class="reference-link" href="Search/Under%20the%20hood.md">Under the hood</a> for more syntax references.diff --git a/packages/commons/src/lib/search_syntax.ts b/packages/commons/src/lib/search_syntax.tsindex c331311e4e..a37b5088f1 100644--- a/packages/commons/src/lib/search_syntax.ts+++ b/packages/commons/src/lib/search_syntax.ts@@ -37,7 +37,7 @@ export const SEARCH_NOTE_PATH = {/** Matched against the note's text through a full-text expression rather than a property. */contentProperties: [ "content", "rawContent", "text" ],/** Step onto another note, so a further segment follows: `note.parents.title`. */- traversals: [ "parents", "children", "ancestors" ],+ traversals: [ "parents", "children", "ancestors", "links", "backlinks" ],/** Expect an attribute name next, which nothing can enumerate ahead of time. */attributeSegments: [ "labels", "relations" ]} as const;diff --git a/packages/trilium-core/src/services/search/expressions/linked_notes.ts b/packages/trilium-core/src/services/search/expressions/linked_notes.tsnew file mode 100644index 0000000000..1ac5288a22--- /dev/null+++ b/packages/trilium-core/src/services/search/expressions/linked_notes.ts@@ -0,0 +1,65 @@+import { BUILTIN_ATTRIBUTES } from "@triliumnext/commons";++import type BAttribute from "../../../becca/entities/battribute.js";+import type BNote from "../../../becca/entities/bnote.js";+import NoteSet from "../note_set.js";+import type SearchContext from "../search_context.js";+import Expression from "./expression.js";++/**+ * `note.links` keeps the notes linking to a note that matches the sub-expression; `note.backlinks`+ * keeps the notes linked from one. A link is a relation the note owns, counted by `isLink()`.+ */+export default class LinkedNotesExp extends Expression {+ private direction: "links" | "backlinks";+ private subExpression: Expression;++ constructor(direction: "links" | "backlinks", subExpression: Expression) {+ super();++ this.direction = direction;+ this.subExpression = subExpression;+ }++ execute(inputNoteSet: NoteSet, executionContext: {}, searchContext: SearchContext) {+ const subInputNoteSet = new NoteSet();++ for (const note of inputNoteSet.notes) {+ subInputNoteSet.addAll(this.linkedNotes(note));+ }++ const matched = this.subExpression.execute(subInputNoteSet, executionContext, searchContext);+ const resNoteSet = new NoteSet();++ for (const note of inputNoteSet.notes) {+ if (this.linkedNotes(note).some((linked) => matched.hasNote(linked))) {+ resNoteSet.add(note);+ }+ }++ return resNoteSet;+ }++ private linkedNotes(note: BNote): BNote[] {+ const relations = this.direction === "links" ? note.getOwnedRelations() : note.getTargetRelations();+ const linked: BNote[] = [];++ for (const relation of relations) {+ const other = this.direction === "links" ? relation.targetNote : relation.note;+ if (other && isLink(relation)) {+ linked.push(other);+ }+ }++ return linked;+ }+}++/** The relations content creates, which are built in but count as links. */+const LINK_RELATIONS = new Set([ "internalLink", "imageLink", "includeNoteLink", "relationMapLink" ]);+const BUILTIN_RELATIONS = new Set(BUILTIN_ATTRIBUTES.filter((attr) => attr.type === "relation").map((attr) => attr.name));++/** A relation the user created, or one of `LINK_RELATIONS`; other built-in relations configure the note. */+export function isLink(relation: BAttribute) {+ return LINK_RELATIONS.has(relation.name) || !BUILTIN_RELATIONS.has(relation.name);+}diff --git a/packages/trilium-core/src/services/search/services/parse.ts b/packages/trilium-core/src/services/search/services/parse.tsindex ab81133d7d..91acdee92e 100644--- a/packages/trilium-core/src/services/search/services/parse.ts+++ b/packages/trilium-core/src/services/search/services/parse.ts@@ -10,6 +10,7 @@ import ParentOfExp from "../expressions/parent_of.js";import RelationWhereExp from "../expressions/relation_where.js";import PropertyComparisonExp from "../expressions/property_comparison.js";import LabelComparisonExp from "../expressions/label_comparison.js";+import LinkedNotesExp from "../expressions/linked_notes.js";import NoteFlatTextExp from "../expressions/note_flat_text.js";import NoteContentFulltextExp from "../expressions/note_content_fulltext.js";import OrderByAndLimitExp from "../expressions/order_by_and_limit.js";@@ -203,6 +204,17 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelreturn new DescendantOfExp(expression);}+ if (tokens[i].token === "links" || tokens[i].token === "backlinks") {+ const direction = tokens[i].token === "links" ? "links" : "backlinks";+ i += 1;++ const expression = parseNoteProperty();+ if (!expression) {+ return;+ }+ return new LinkedNotesExp(direction, expression);+ }+if (tokens[i].token === "labels") {if (tokens[i + 1].token !== ".") {searchContext.addError(`Expected "." to separate field path, got "${tokens[i + 1].token}" in ${context(i)}`);diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex 580b12beb7..3bc26b77fc 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -561,6 +561,25 @@ describe("Search", () => {expect(findNoteByTitle(searchResults, "Taipei")).toBeTruthy();});+ it("follows links and backlinks, counting user relations and link types but not built-in ones", () => {+ const tolkien = note("Tolkien");+ const essay = note("Essay").relation("internalLink", tolkien.note);+ const book = note("The Hobbit").relation("author", tolkien.note);+ const fromTemplate = note("Created from Tolkien").relation("template", tolkien.note);+ const savedSearch = note("Search under Tolkien", { type: "search" }).relation("ancestor", tolkien.note);+ rootNote.child(tolkien).child(essay).child(book).child(fromTemplate).child(savedSearch);++ const titles = (query: string) => searchService.findResultsWithQuery(query, new SearchContext())+ .map((result) => becca.notes[result.noteId].title)+ .sort();++ expect(titles("note.links.title = Tolkien")).toEqual([ "Essay", "The Hobbit" ]);+ expect(titles(`note.links.noteId = ${tolkien.note.noteId}`)).toEqual([ "Essay", "The Hobbit" ]);+ expect(titles("note.backlinks.title = Essay")).toEqual([ "Tolkien" ]);+ expect(titles("note.backlinks.title = 'Created from Tolkien'")).toEqual([]);+ expect(titles("note.title = Tolkien AND note.backlinks.title *=* o")).toEqual([ "Tolkien" ]);+ });+it("filter by note's child", () => {rootNote.child(note("Europe")