Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(fts5): add fts filter on update/delete document from index (#1312)

Corentin Thomassetaded8322985b
diff --git a/.changeset/crazy-breads-shine.md b/.changeset/crazy-breads-shine.md
new file mode 100644
index 00000000..aeef45fc
--- /dev/null
+++ b/.changeset/crazy-breads-shine.md
@@ -0,0 +1,5 @@
+---
+'@papra/app': patch
+---
+
+Greatly improved the performances when updating and deleting document from the sezarch index, avoiding unnecessary table scans. Noticeable improvement on large document collections (10k+ documents).
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.test.ts
new file mode 100644
index 00000000..f678579d
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from 'vitest';
+import { buildFts5ColumnMatchTerm } from './database-fts5.models';
+
+describe('database-fts5 models', () => {
+ describe('buildFts5ColumnMatchTerm', () => {
+ test('multiple column names are joined with a space and wrapped in curly braces', () => {
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name', 'content'],
+ value: 'foo',
+ isExactMatch: false,
+ }),
+ ).to.eql('{name content}:"foo"*');
+
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name', 'content', 'notes'],
+ value: 'foo',
+ isExactMatch: false,
+ }),
+ ).to.eql('{name content notes}:"foo"*');
+
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name', 'content'],
+ value: 'foo',
+ isExactMatch: true,
+ }),
+ ).to.eql('{name content}:"foo"');
+ });
+
+ test('single column name is not wrapped in curly braces', () => {
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name'],
+ value: 'foo',
+ isExactMatch: false,
+ }),
+ ).to.eql('name:"foo"*');
+
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name'],
+ value: 'foo',
+ isExactMatch: true,
+ }),
+ ).to.eql('name:"foo"');
+ });
+
+ test('no column names results in a query atom without column prefix', () => {
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: [],
+ value: 'foo',
+ isExactMatch: false,
+ }),
+ ).to.eql('"foo"*');
+
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: [],
+ value: 'foo',
+ isExactMatch: true,
+ }),
+ ).to.eql('"foo"');
+ });
+
+ test('value is wrapped in double quotes, and other quotes are replaced with spaces in order to preserve tokenization', () => {
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name'],
+ value: `c'est "foo"`,
+ isExactMatch: false,
+ }),
+ ).to.eql('name:"c est foo "*');
+ });
+
+ test('non exact match appends a wildcard to the value for prefixed search', () => {
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name'],
+ value: 'foo',
+ isExactMatch: false,
+ }),
+ ).to.eql('name:"foo"*');
+
+ expect(
+ buildFts5ColumnMatchTerm({
+ columnNames: ['name'],
+ value: 'foo',
+ isExactMatch: true,
+ }),
+ ).to.eql('name:"foo"');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.ts
new file mode 100644
index 00000000..5f02ec57
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.models.ts
@@ -0,0 +1,23 @@
+export function buildFts5ColumnMatchTerm({
+ columnNames,
+ value,
+ isExactMatch,
+}: {
+ columnNames: string[];
+ value: string;
+ isExactMatch: boolean;
+}): string {
+ const sanitizedValue = value.trim().replace(/["'‘’“”]/g, ' '); // Replace various quote characters with space so they don't interfere with FTS5 syntax
+ const quotedValue = `"${sanitizedValue}"`;
+ const formattedValue = isExactMatch ? quotedValue : `${quotedValue}*`;
+
+ if (columnNames.length === 0) {
+ return formattedValue;
+ }
+
+ if (columnNames.length === 1) {
+ return `${columnNames[0]}:${formattedValue}`;
+ }
+
+ return `{${columnNames.join(' ')}}:${formattedValue}`;
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
index 82f2f879..5cceb1dd 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
@@ -2,7 +2,7 @@ import type { Database } from '../../../app/database/database.types';
import type { DocumentSearchSort } from '../document-search.constants';
import type { DocumentSearchableData, DocumentUpdate } from '../document-search.types';
import { injectArguments } from '@corentinth/chisels';
-import { eq, getTableColumns, inArray, sql } from 'drizzle-orm';
+import { and, eq, getTableColumns, inArray, sql } from 'drizzle-orm';
import { customPropertyDefinitionsTable } from '../../../custom-properties/custom-properties.table';
import { isNonEmptyArray } from '../../../shared/arrays/arrays.utils';
import { omit, omitUndefined } from '../../../shared/objects';
@@ -10,6 +10,7 @@ import { documentsTable } from '../../documents.table';
import { DEFAULT_DOCUMENT_SEARCH_SORT } from '../document-search.constants';
import { makeSearchOrderByClauses, makeSearchWhereClause } from './database-fts5.repository.models';
import { documentsFtsTable } from './database-fts5.tables';
+import { buildFts5ColumnMatchTerm } from './database-fts5.models';
export type DocumentSearchRepository = ReturnType<typeof createDocumentSearchRepository>;
@@ -160,7 +161,19 @@ async function updateDocuments({ updates, db }: { updates: DocumentUpdate[]; db:
return db
.update(documentsFtsTable)
.set(dataToUpdate)
- .where(eq(documentsFtsTable.documentId, documentId));
+ .where(
+ and(
+ eq(documentsFtsTable.documentId, documentId),
+ eq(
+ documentsFtsTable,
+ buildFts5ColumnMatchTerm({
+ columnNames: [documentsFtsTable.documentId.name],
+ value: documentId,
+ isExactMatch: true,
+ }),
+ ),
+ ),
+ );
})
.filter((query) => query !== null);
@@ -176,5 +189,21 @@ async function deleteDocuments({ documentIds, db }: { documentIds: string[]; db:
return;
}
- await db.delete(documentsFtsTable).where(inArray(documentsFtsTable.documentId, documentIds));
+ await db.delete(documentsFtsTable).where(
+ and(
+ inArray(documentsFtsTable.documentId, documentIds),
+ eq(
+ documentsFtsTable,
+ documentIds
+ .map((documentId) =>
+ buildFts5ColumnMatchTerm({
+ columnNames: [documentsFtsTable.documentId.name],
+ value: documentId,
+ isExactMatch: true,
+ }),
+ )
+ .join(' OR '),
+ ),
+ ),
+ );
}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.test.ts
index 99314729..fadad2bf 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.test.ts
@@ -22,7 +22,7 @@ describe('query-builder models', () => {
matchingColumns: ['name'],
}),
).to.eql({
- queryString: 'organization_id:"org_1" {name}:"foobar"*',
+ queryString: 'organization_id:"org_1" name:"foobar"*',
});
});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.ts
index 0de41769..79540dd9 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.ts
@@ -3,10 +3,7 @@ import type { BinaryOperator } from 'drizzle-orm';
import type { QueryResult } from './query-builder.types';
import { eq, gt, gte, lt, lte, sql } from 'drizzle-orm';
import { documentsFtsTable } from '../database-fts5.tables';
-
-function joinColumnNames(columns: string[]): string {
- return columns.join(' ');
-}
+import { buildFts5ColumnMatchTerm } from '../database-fts5.models';
export function formatFts5QueryValue({
value,
@@ -17,13 +14,17 @@ export function formatFts5QueryValue({
organizationId: string;
matchingColumns?: string[];
}) {
- const formattedValue = value.trim().replace(/["'‘’“”]/g, ' '); // Replace various quote characters with space so they don't interfere with FTS5 syntax
-
const queryString = [
- `${documentsFtsTable.organizationId.name}:"${organizationId}"`,
- matchingColumns.length === 0
- ? `"${formattedValue}"*`
- : `{${joinColumnNames(matchingColumns)}}:"${formattedValue}"*`,
+ buildFts5ColumnMatchTerm({
+ columnNames: [documentsFtsTable.organizationId.name],
+ value: organizationId,
+ isExactMatch: true,
+ }),
+ buildFts5ColumnMatchTerm({
+ columnNames: matchingColumns,
+ value,
+ isExactMatch: false,
+ }),
].join(' ');
return { queryString };
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.test.ts
index 7dc9218b..9874c2d4 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.test.ts
@@ -32,7 +32,7 @@ describe('query-builder', async () => {
expect(stringifySqlQuery(sqlQuery)).to.eql({
query: `"documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?)`,
- params: ['organization_id:"org_1" {name}:"important"*'],
+ params: ['organization_id:"org_1" name:"important"*'],
});
});
@@ -47,7 +47,7 @@ describe('query-builder', async () => {
expect(stringifySqlQuery(sqlQuery)).to.eql({
query: `"documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?)`,
- params: ['organization_id:"org_1" {name}:"important (draft)"*'],
+ params: ['organization_id:"org_1" name:"important (draft)"*'],
});
});
@@ -81,7 +81,7 @@ describe('query-builder', async () => {
expect(stringifySqlQuery(sqlQuery)).to.eql({
query: `"documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?)`,
- params: ['organization_id:"org_1" {content}:"confidential"*'],
+ params: ['organization_id:"org_1" content:"confidential"*'],
});
});
@@ -96,7 +96,7 @@ describe('query-builder', async () => {
expect(stringifySqlQuery(sqlQuery)).to.eql({
query: `"documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?)`,
- params: ['organization_id:"org_1" {content}:"confidential [v2]"*'],
+ params: ['organization_id:"org_1" content:"confidential [v2]"*'],
});
});
@@ -445,7 +445,7 @@ describe('query-builder', async () => {
query: `("documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?) and "documents"."id" in (select distinct "document_id" from "documents_fts" where "documents_fts" = ?))`,
params: [
'organization_id:"org_1" {name content}:"invoice"*',
- 'organization_id:"org_1" {name}:"Q3"*',
+ 'organization_id:"org_1" name:"Q3"*',
],
});
});