Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

core: use better_trigram for improved content tokenization

Abdullah Atta1f24fd4758f0
diff --git a/packages/core/__tests__/utils/index.ts b/packages/core/__tests__/utils/index.ts
index 5bb06a53c..dc7c4d84e 100644
--- a/packages/core/__tests__/utils/index.ts
+++ b/packages/core/__tests__/utils/index.ts
@@ -30,6 +30,7 @@ import path from "path";
import { tmpdir } from "os";
import { getId } from "../../src/utils/id.js";
import { existsSync, mkdirSync } from "fs";
+import * as betterTrigram from "sqlite-better-trigram";
const TEST_NOTEBOOK: Partial<Notebook> = {
title: "Test Notebook",
@@ -46,6 +47,9 @@ function databaseTest(type: "memory" | "persistent" = "memory") {
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
const dbPath = path.join(dir, `notesnook-${getId()}.sql`);
const db = new DB();
+ const betterSqliteDb = BetterSQLite3(
+ type === "persistent" ? dbPath : ":memory:"
+ ).unsafeMode(true);
db.setup({
storage: new NodeStorageInterface(),
eventsource: EventSource,
@@ -54,14 +58,13 @@ function databaseTest(type: "memory" | "persistent" = "memory") {
sqliteOptions: {
dialect: (name) =>
new SqliteDialect({
- database: BetterSQLite3(
- type === "persistent" ? dbPath : ":memory:"
- ).unsafeMode(true)
+ database: betterSqliteDb
}),
password: type === "persistent" ? "iamalongpassword" : undefined
},
batchSize: 500
});
+ betterTrigram.load(betterSqliteDb);
return db.init().then(() => db);
}
diff --git a/packages/core/package-lock.json b/packages/core/package-lock.json
index 9339315ac..468114138 100644
--- a/packages/core/package-lock.json
+++ b/packages/core/package-lock.json
@@ -32,7 +32,8 @@
"prismjs": "^1.29.0",
"qclone": "^1.2.0",
"rfdc": "^1.3.0",
- "spark-md5": "^3.0.2"
+ "spark-md5": "^3.0.2",
+ "sqlite-better-trigram": "^0.0.1"
},
"devDependencies": {
"@notesnook/crypto": "file:../crypto",
@@ -4207,6 +4208,70 @@
"version": "3.0.2",
"license": "(WTFPL OR MIT)"
},
+ "node_modules/sqlite-better-trigram": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/sqlite-better-trigram/-/sqlite-better-trigram-0.0.1.tgz",
+ "integrity": "sha512-2FhkGhVJVBVaLYXdwbF682WnYr1rnOnikyocGZp1nzUgN14n78AJONp8BcKME+AlJRf0z1zDmlwKstFkXzHr4Q==",
+ "license": "Public Domain",
+ "optionalDependencies": {
+ "sqlite-better-trigram-darwin-arm64": "0.0.1",
+ "sqlite-better-trigram-darwin-x64": "0.0.1",
+ "sqlite-better-trigram-linux-x64": "0.0.1",
+ "sqlite-better-trigram-windows-x64": "0.0.1"
+ }
+ },
+ "node_modules/sqlite-better-trigram-darwin-arm64": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/sqlite-better-trigram-darwin-arm64/-/sqlite-better-trigram-darwin-arm64-0.0.1.tgz",
+ "integrity": "sha512-FtjNgstN2izg3m/jMqUbFWbqZvrSJBxfOC2Uo3Q+tsdTFAc+QZxmSWK29+FbHgkMw1yB4wkjuHtBoLgrjjp0yw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Public Domain",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/sqlite-better-trigram-darwin-x64": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/sqlite-better-trigram-darwin-x64/-/sqlite-better-trigram-darwin-x64-0.0.1.tgz",
+ "integrity": "sha512-DA+C7sp10hGS09m4QwkTvXQQJB7EqKMD/bK8cBXXhOVhL99lmjqZnQZrtqoPVO2DFwoh5osCPXDCiWy2TfBrwQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Public Domain",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/sqlite-better-trigram-linux-x64": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/sqlite-better-trigram-linux-x64/-/sqlite-better-trigram-linux-x64-0.0.1.tgz",
+ "integrity": "sha512-9vLIxhIzOzXLe3K2dYj0ZYbDDRSXzWUraZ6bcBqGqmOAFceuGGeMFPgaw/h+aUCHVm2GaHHLdkO3iX+7VZzhXg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Public Domain",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/sqlite-better-trigram-windows-x64": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/sqlite-better-trigram-windows-x64/-/sqlite-better-trigram-windows-x64-0.0.1.tgz",
+ "integrity": "sha512-4E2SgURd6F9xVk9FWdknJNfNMaGjJDYe0KTPGE7Omja/JUPaE+lq2i6Uc7asqJ1y/G+oMY1P+8MdGUB6N75xaQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Public Domain",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/stackback": {
"version": "0.0.2",
"dev": true,
diff --git a/packages/core/package.json b/packages/core/package.json
index 9741629ea..34986c62b 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -84,7 +84,8 @@
"prismjs": "^1.29.0",
"qclone": "^1.2.0",
"rfdc": "^1.3.0",
- "spark-md5": "^3.0.2"
+ "spark-md5": "^3.0.2",
+ "sqlite-better-trigram": "^0.0.1"
},
"overrides": {
"htmlparser2": "^8.0.1"
diff --git a/packages/core/src/api/lookup.ts b/packages/core/src/api/lookup.ts
index 1fae6b974..920447efe 100644
--- a/packages/core/src/api/lookup.ts
+++ b/packages/core/src/api/lookup.ts
@@ -47,53 +47,60 @@ export default class Lookup {
const db = this.db.sql() as unknown as Kysely<RawDatabaseSchema>;
const excludedIds = this.db.trash.cache.notes;
- if (query.length <= 2) {
- const results = await db
- .selectFrom((eb) =>
- eb
- .selectFrom("notes")
- .$if(!!notes, (eb) =>
- eb.where("id", "in", notes!.filter.select("id"))
- )
- .$if(excludedIds.length > 0, (eb) =>
- eb.where("id", "not in", excludedIds)
- )
- .where("title", "like", `%${query}%`)
- .select(["id"])
- .unionAll((eb) =>
- eb
- .selectFrom("content")
- .$if(!!notes, (eb) =>
- eb.where("id", "in", notes!.filter.select("id"))
- )
- .$if(excludedIds.length > 0, (eb) =>
- eb.where("id", "not in", excludedIds)
- )
- .where("locked", "!=", true)
- .where("data", "like", `%${query}%`)
- .select(["noteId as id"])
- .$castTo<{ id: string; dateCreated: number }>()
- )
- .as("results")
- )
- .select(["results.id"])
- .groupBy("results.id")
- .$if(!!limit, (eb) => eb.limit(limit!))
- // filter out ids that have no note against them
- .where(
- "results.id",
- "in",
- (notes || this.db.notes.all).filter.select("id")
- )
- .execute()
- .catch((e) => {
- logger.error(e, `Error while searching`, { query });
- return [];
- });
- return results.map((r) => r.id);
- }
+ // if (query.length <= 2) {
+ // const results = await db
+ // .selectFrom((eb) =>
+ // eb
+ // .selectFrom("notes")
+ // .$if(!!notes, (eb) =>
+ // eb.where("id", "in", notes!.filter.select("id"))
+ // )
+ // .$if(excludedIds.length > 0, (eb) =>
+ // eb.where("id", "not in", excludedIds)
+ // )
+ // .where("title", "like", `%${query}%`)
+ // .select(["id"])
+ // .unionAll((eb) =>
+ // eb
+ // .selectFrom("content")
+ // .$if(!!notes, (eb) =>
+ // eb.where("id", "in", notes!.filter.select("id"))
+ // )
+ // .$if(excludedIds.length > 0, (eb) =>
+ // eb.where("id", "not in", excludedIds)
+ // )
+ // .where("locked", "!=", true)
+ // .where("data", "like", `%${query}%`)
+ // .select(["noteId as id"])
+ // .$castTo<{ id: string; dateCreated: number }>()
+ // )
+ // .as("results")
+ // )
+ // .select(["results.id"])
+ // .groupBy("results.id")
+ // .$if(!!limit, (eb) => eb.limit(limit!))
+ // // filter out ids that have no note against them
+ // .where(
+ // "results.id",
+ // "in",
+ // (notes || this.db.notes.all).filter.select("id")
+ // )
+ // .execute()
+ // .catch((e) => {
+ // logger.error(e, `Error while searching`, { query });
+ // return [];
+ // });
+ // return results.map((r) => r.id);
+ // }
query = transformQuery(query);
+ console.log(
+ "TRANSFORMED",
+ query,
+ await sql`SELECT * from content_fts where data MATCH 'awesome'`.execute(
+ db
+ )
+ );
const results = await db
.selectFrom((eb) =>
eb
diff --git a/packages/core/src/database/migrations.ts b/packages/core/src/database/migrations.ts
index e28bee5d7..21688896a 100644
--- a/packages/core/src/database/migrations.ts
+++ b/packages/core/src/database/migrations.ts
@@ -333,6 +333,31 @@ export class NNMigrationProvider implements MigrationProvider {
}
},
"6": {
+ async up(db) {
+ // await db.transaction().execute(async (tx) => {
+ // await tx.schema.dropTable("content_fts").execute();
+ // await tx.schema.dropTable("notes_fts").execute();
+ // await createFTS5Table(
+ // "notes_fts",
+ // [{ name: "id" }, { name: "title" }],
+ // {
+ // contentTable: "notes",
+ // tokenizer: ["porter", "trigram", "remove_diacritics 1"]
+ // }
+ // ).execute(tx);
+ // await createFTS5Table(
+ // "content_fts",
+ // [{ name: "id" }, { name: "noteId" }, { name: "data" }],
+ // {
+ // contentTable: "content",
+ // tokenizer: ["porter", "trigram", "remove_diacritics 1"]
+ // }
+ // ).execute(tx);
+ // });
+ // await rebuildSearchIndex(db);
+ }
+ },
+ "7": {
async up(db) {
await db.transaction().execute(async (tx) => {
await tx.schema.dropTable("content_fts").execute();
@@ -343,7 +368,7 @@ export class NNMigrationProvider implements MigrationProvider {
[{ name: "id" }, { name: "title" }],
{
contentTable: "notes",
- tokenizer: ["porter", "trigram", "remove_diacritics 1"]
+ tokenizer: ["porter", "better_trigram", "remove_diacritics 1"]
}
).execute(tx);
@@ -352,7 +377,7 @@ export class NNMigrationProvider implements MigrationProvider {
[{ name: "id" }, { name: "noteId" }, { name: "data" }],
{
contentTable: "content",
- tokenizer: ["porter", "trigram", "remove_diacritics 1"]
+ tokenizer: ["porter", "better_trigram", "remove_diacritics 1"]
}
).execute(tx);
});
diff --git a/packages/core/src/utils/__tests__/query-transformer.test.ts b/packages/core/src/utils/__tests__/query-transformer.test.ts
index 8ad04037c..fbac61561 100644
--- a/packages/core/src/utils/__tests__/query-transformer.test.ts
+++ b/packages/core/src/utils/__tests__/query-transformer.test.ts
@@ -21,45 +21,45 @@ import { expect, test } from "vitest";
import { transformQuery } from "../query-transformer.js";
const TRANSFORM_QUERY_TESTS = [
- ["hello world", `"hello world"`],
- ["hello world OR bar", `"hello world" OR "bar"`],
- ["hello world OR bar NOT baz", `"hello world" OR "bar" NOT "baz"`],
- ["hello world OR NOT AND", `"hello world"`],
- ["hello world OR NOT AND something", `"hello world" AND "something"`],
- ["hello world -foo", `"hello world -foo"`],
- ["hello world phrase-with-dash", `"hello world phrase-with-dash"`],
- ["hello world phrase-with-dash*", '"hello world phrase-with-dash*"'],
- ["example + foo + bar", `"example + foo + bar"`],
- ["example OR foo NOT bar", `"example" OR "foo" NOT "bar"`],
+ ["hello world", `hello AND world`],
+ ["hello world OR bar", `hello AND world OR bar`],
+ ["hello world OR bar NOT baz", `hello AND world OR bar NOT baz`],
+ ["hello world OR NOT AND", `hello AND world`],
+ ["hello world OR NOT AND something", `hello AND world AND something`],
+ ["hello world -foo", `hello AND world AND "-foo"`],
+ ["hello world phrase-with-dash", `hello AND world AND "phrase-with-dash"`],
+ ["hello world phrase-with-dash*", 'hello AND world AND "phrase-with-dash*"'],
+ ["example + foo + bar", `example AND + AND foo AND + AND bar`],
+ ["example OR foo NOT bar", `example OR foo NOT bar`],
[
'example "quoted phrase" "another quoted phrase"',
- `"example ""quoted phrase"" ""another quoted phrase"""`
+ `example AND "quoted phrase" AND "another quoted phrase"`
],
- ['"phrase-with-dash*"', `""phrase-with-dash*""`],
- ['-foo + bar OR "quoted-phrase"', '"-foo + bar" OR ""quoted-phrase""'],
+ ['"phrase-with-dash*"', `"phrase-with-dash*"`],
+ ['-foo + bar OR "quoted-phrase"', '"-foo" AND + AND bar OR "quoted-phrase"'],
[
'phrase-with-dash* + "quoted-phrase"',
- '"phrase-with-dash* + ""quoted-phrase"""'
+ '"phrase-with-dash*" AND + AND "quoted-phrase"'
],
[
'example -foo + bar + "quoted-dash-phrase*" OR "another-quoted-phrase"',
- '"example -foo + bar + ""quoted-dash-phrase*""" OR ""another-quoted-phrase""'
+ 'example AND "-foo" AND + AND bar AND + AND "quoted-dash-phrase*" OR "another-quoted-phrase"'
],
["", ""],
- ["foo", `"foo"`],
- ['"quoted"', '""quoted""'],
- ["-foo -bar", `"-foo -bar"`],
- ["foo + + bar", `"foo + + bar"`],
- ["foo + OR", `"foo +"`],
- ['"special -phrase*"', '""special -phrase*""'],
- ["foo* + bar*", `"foo* + bar*"`],
- ["(foo + bar) -baz", `"(foo + bar) -baz"`],
- ['"phrase with "quotes""', '""phrase with ""quotes""""'],
- ['foo + "bar -baz" OR "qux*"', '"foo + ""bar -baz""" OR ""qux*""'],
- ["foo + bar + ", `"foo + bar +"`],
- ["+foo bar", `"+foo bar"`],
+ ["foo", `foo`],
+ ['"quoted"', '"quoted"'],
+ ["-foo -bar", `"-foo" AND "-bar"`],
+ ["foo + + bar", `foo AND + AND + AND bar`],
+ ["foo + OR", `foo AND +`],
+ ['"special -phrase*"', '"special -phrase*"'],
+ ["foo* + bar*", `"foo*" AND + AND "bar*"`],
+ ["(foo + bar) -baz", `(foo AND + AND bar) AND "-baz"`],
+ ['"phrase with "quotes""', '"phrase with ""quotes"""'],
+ ['foo + "bar -baz" OR "qux*"', 'foo AND + AND "bar -baz" OR "qux*"'],
+ ["foo + bar + ", `foo AND + AND bar AND +`],
+ ["+foo bar", `+foo AND bar`],
["foo*bar*", `"foo*bar*"`],
- ['"escaped "quotes""', '""escaped ""quotes""""'],
+ ['"escaped "quotes""', '"escaped ""quotes"""'],
["-hello-world", `"-hello-world"`],
["-hello-world*", '"-hello-world*"'],
["*helo*", `"*helo*"`]
diff --git a/packages/core/src/utils/query-transformer.ts b/packages/core/src/utils/query-transformer.ts
index 422533a17..0399f2045 100644
--- a/packages/core/src/utils/query-transformer.ts
+++ b/packages/core/src/utils/query-transformer.ts
@@ -39,14 +39,17 @@ function escapeSQLString(str: string): string {
return `"${innerStr}"`;
}
- // const isSubstitution = str.startsWith("-");
- // if (isSubstitution) {
- // return str.replace(/^-(.+)/g, (_, rest) => {
- // return `-${escapeSQLString(rest)}`;
- // });
- // }
+ const maybeColspec =
+ str.startsWith("-") || str.endsWith(":") || str.includes("-");
+ const isWildcard =
+ str.startsWith("*") ||
+ str.endsWith("*") ||
+ str.startsWith("%") ||
+ str.endsWith("%");
+ if (maybeColspec || isWildcard) {
+ return `"${str}"`;
+ }
- // const isWildcard = str.endsWith("*");
// if (isWildcard) {
// return str.replace(/(.+?)(\*?$)/gm, (_, text, end) => {
// return `${escapeSQLString(text)}${end}`;
@@ -118,10 +121,10 @@ function transformAST(ast: QueryNode): QueryNode {
if (lastWasPhrase) {
transformedAST.children.push({ type: "AND" });
}
- // const transformedPhrase = child.value;//.map(escapeSQLString);
+ const transformedPhrase = child.value.map(escapeSQLString);
transformedAST.children.push({
type: "phrase",
- value: child.value
+ value: transformedPhrase
});
lastWasPhrase = true;
} else if (
@@ -147,7 +150,7 @@ function generateSQL(ast: QueryNode): string {
return ast.children
.map((child) => {
if (child.type === "phrase") {
- return `"${escapeSQLString(child.value.join(" "))}"`;
+ return child.value.join(" AND ");
}
if (child.type === "AND" || child.type === "OR" || child.type === "NOT") {
return child.type;