Initial search implementation

This commit is contained in:
Zef Hemel
2022-05-16 15:09:36 +02:00
parent 7d01f77318
commit 2cdd3df6c3
17 changed files with 14798 additions and 62 deletions
@@ -0,0 +1,42 @@
import { Knex } from "knex";
import { SysCallMapping } from "../system";
type Item = {
key: string;
value: string;
};
export async function ensureFTSTable(
db: Knex<any, unknown>,
tableName: string
) {
if (!(await db.schema.hasTable(tableName))) {
await db.raw(`CREATE VIRTUAL TABLE ${tableName} USING fts5(key, value);`);
console.log(`Created fts5 table ${tableName}`);
}
}
export function fullTextSearchSyscalls(
db: Knex<any, unknown>,
tableName: string
): SysCallMapping {
return {
"fulltext.index": async (ctx, key: string, value: string) => {
await db<Item>(tableName).where({ key }).del();
await db<Item>(tableName).insert({ key, value });
},
"fulltext.delete": async (ctx, key: string) => {
await db<Item>(tableName).where({ key }).del();
},
"fulltext.search": async (ctx, phrase: string, limit: number) => {
return (
await db<any>(tableName)
.whereRaw(`value MATCH ?`, [phrase])
.select(["key", "rank"])
.orderBy("rank")
.limit(limit)
).map((item) => ({ name: item.key, rank: item.rank }));
},
};
}
@@ -19,6 +19,7 @@ export async function ensureTable(db: Knex<any, unknown>, tableName: string) {
table.text("value");
table.primary(["key"]);
});
console.log(`Created table ${tableName}`);
}
}