Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(search-query): integrate search-parser for enhanced query handling (#746)

Corentin Thomasset685f03c2fcbb
diff --git a/.changeset/real-onions-jog.md b/.changeset/real-onions-jog.md
new file mode 100644
index 00000000..5f0ea52c
--- /dev/null
+++ b/.changeset/real-onions-jog.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Added advanced search syntax support
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index caa1a6e0..1fcc704f 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -55,6 +55,7 @@
"@owlrelay/api-sdk": "^0.0.2",
"@owlrelay/webhook": "^0.0.3",
"@papra/lecture": "workspace:*",
+ "@papra/search-parser": "workspace:*",
"@papra/webhooks": "workspace:*",
"@paralleldrive/cuid2": "^2.2.2",
"@sindresorhus/slugify": "^3.0.0",
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.test.ts
index 04d0268a..05edfffa 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.test.ts
@@ -1,107 +1,59 @@
+import type { SQL } from 'drizzle-orm';
+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
import { describe, expect, test } from 'vitest';
-import { createFts5DocumentSearchQuery, formatFts5SearchQuery } from './database-fts5.repository.models';
+import { createInMemoryDatabase } from '../../../app/database/database.test-utils';
+import { makeSearchWhereClause } from './database-fts5.repository.models';
describe('database-fts5 repository models', () => {
- describe('formatFts5SearchQuery', () => {
- test('wraps single word with quotes and appends wildcard', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: 'documents' }),
- ).to.eql({
- formattedSearchQuery: '"documents"*',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: 'hello world' }),
- ).to.eql({
- formattedSearchQuery: '"hello"* "world"*',
- });
- });
-
- test('whitespaces are trimmed and reduced to single spaces', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: ' multiple spaces here ' }),
- ).to.eql({
- formattedSearchQuery: '"multiple"* "spaces"* "here"*',
- });
- });
-
- test('special characters are removed except hyphens and underscores', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: 'special! @#characters$ %^&*()here' }),
- ).to.eql({
- formattedSearchQuery: '"special"* "characters"* "here"*',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: '"hello world"' }),
- ).to.eql({
- formattedSearchQuery: '"hello"* "world"*',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: 'hyphen-word_and_underscore' }),
- ).to.eql({
- formattedSearchQuery: '"hyphen-word_and_underscore"*',
+ describe('makeSearchWhereClause', async () => {
+ const { db } = await createInMemoryDatabase();
+
+ const sqliteDialect = new SQLiteSyncDialect();
+ const getSqlString = (query?: SQL) => {
+ if (!query) {
+ return { sql: '', params: [] };
+ }
+
+ const { sql, params } = sqliteDialect.sqlToQuery(query);
+ return { sql, params };
+ };
+
+ test('a simple text query', () => {
+ const { issues, searchWhereClause } = makeSearchWhereClause({ organizationId: 'org_1', query: 'foo', db });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(searchWhereClause)).to.eql({
+ sql: `(\"documents\".\"organization_id\" = ? and \"documents\".\"is_deleted\" = ? and \"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?))`,
+ params: [
+ 'org_1',
+ 0,
+ 'organization_id:"org_1" {name content}:"foo"*',
+ ],
});
});
- test('boolean operators are removed', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: 'apple AND orange OR banana NOT grape' }),
- ).to.eql({
- formattedSearchQuery: '"apple"* "orange"* "banana"* "grape"*',
+ test('a complex query', () => {
+ const { issues, searchWhereClause } = makeSearchWhereClause({
+ organizationId: 'org_1',
+ query: '(tag:important OR tag:urgent) AND NOT confidential',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(searchWhereClause)).to.eql({
+ sql: `(\"documents\".\"organization_id\" = ? and \"documents\".\"is_deleted\" = ? and ((\"documents\".\"id\" in (select distinct \"documents_tags\".\"document_id\" from \"documents_tags\" inner join \"tags\" on \"documents_tags\".\"tag_id\" = \"tags\".\"id\" where (\"tags\".\"organization_id\" = ? and (\"tags\".\"name\" = ? or \"tags\".\"id\" = ?))) or \"documents\".\"id\" in (select distinct \"documents_tags\".\"document_id\" from \"documents_tags\" inner join \"tags\" on \"documents_tags\".\"tag_id\" = \"tags\".\"id\" where (\"tags\".\"organization_id\" = ? and (\"tags\".\"name\" = ? or \"tags\".\"id\" = ?)))) and not \"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)))`,
+ params: [
+ 'org_1',
+ 0,
+ 'org_1',
+ 'important',
+ 'important',
+ 'org_1',
+ 'urgent',
+ 'urgent',
+ 'organization_id:\"org_1\" {name content}:\"confidential\"*',
+ ],
});
-
- expect(
- formatFts5SearchQuery({ searchQuery: 'apple or orange' }),
- ).to.eql({
- formattedSearchQuery: '"apple"* "orange"*',
- });
- });
-
- test('empty or whitespace-only queries return empty formatted query', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: ' ' }),
- ).to.eql({
- formattedSearchQuery: '',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: '' }),
- ).to.eql({
- formattedSearchQuery: '',
- });
- });
-
- test('special language characters are preserved', () => {
- expect(
- formatFts5SearchQuery({ searchQuery: 'café naïve jalapeño façade' }),
- ).to.eql({
- formattedSearchQuery: '"café"* "naïve"* "jalapeño"* "façade"*',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: 'добрый день привет' }),
- ).to.eql({
- formattedSearchQuery: '"добрый"* "день"* "привет"*',
- });
-
- expect(
- formatFts5SearchQuery({ searchQuery: 'こんにちは 世界' }),
- ).to.eql({
- formattedSearchQuery: '"こんにちは"* "世界"*',
- });
- });
- });
-
- describe('createFts5DocumentSearchQuery', () => {
- test('combines organization filter with formatted search query', () => {
- const { query } = createFts5DocumentSearchQuery({
- searchQuery: 'test search',
- organizationId: 'org123',
- });
-
- expect(query).toBe('organization_id:"org123" "test"* "search"*');
});
});
});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
index 1bde172b..6627496f 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
@@ -1,30 +1,20 @@
-import { documentsFtsTable } from './database-fts5.tables';
+import type { Database } from '../../../app/database/database.types';
+import { parseSearchQuery } from '@papra/search-parser';
+import { and, eq } from 'drizzle-orm';
+import { documentsTable } from '../../documents.table';
+import { buildQueryFromExpression } from './query-builder/query-builder';
-export function formatFts5SearchQuery({ searchQuery }: { searchQuery: string }) {
- const formattedSearchQuery = searchQuery
- .trim()
- .replace(/[^\p{L}\p{N}\s\-_]/gu, '') // Remove special characters except hyphens and underscores, preserve Unicode letters/numbers
- .replace(/\b(?:AND|OR|NOT)\b/gi, ' ') // Remove boolean operators
- .split(/\s+/)
- .filter(token => token.length > 0)
- .map(token => `"${token}"*`)
- .join(' ');
+export function makeSearchWhereClause({ query, organizationId, db }: { query: string; organizationId: string; db: Database }) {
+ const { expression, issues: parsedIssues } = parseSearchQuery({ query });
- return { formattedSearchQuery };
-}
-
-export function createFts5DocumentSearchQuery({
- searchQuery,
- organizationId,
- organizationIdColumnName = documentsFtsTable.organizationId.name,
-}: {
- searchQuery: string;
- organizationId: string;
- organizationIdColumnName?: string;
-}) {
- const { formattedSearchQuery } = formatFts5SearchQuery({ searchQuery });
-
- const query = `${organizationIdColumnName}:"${organizationId}" ${formattedSearchQuery}`;
+ const { sqlQuery, issues } = buildQueryFromExpression({ expression, organizationId, db });
- return { query };
+ return {
+ searchWhereClause: and(
+ eq(documentsTable.organizationId, organizationId),
+ eq(documentsTable.isDeleted, false),
+ sqlQuery,
+ ),
+ issues: [...parsedIssues, ...issues],
+ };
}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
index 8b146988..ba949bb0 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
@@ -7,13 +7,13 @@ describe('database-fts5 repository', () => {
describe('searchOrganizationDocuments', () => {
test('provides full text search on document name, original name, and content', async () => {
const documents = [
- { id: 'doc-1', organizationId: 'organization-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
- { id: 'doc-2', organizationId: 'organization-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
- { id: 'doc-3', organizationId: 'organization-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ { id: 'doc_1', organizationId: 'org_1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
];
const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
documents,
});
@@ -24,29 +24,205 @@ describe('database-fts5 repository', () => {
);
const { documents: searchResults } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'lorem',
pageIndex: 0,
pageSize: 10,
});
expect(searchResults).to.have.length(2);
- expect(searchResults.map(doc => doc.id)).to.eql(['doc-2', 'doc-1']);
+ expect(searchResults.map(doc => doc.id).toSorted()).to.eql(['doc_1', 'doc_2']);
+ });
+
+ test('search query can have special characters', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'c\'est énorme', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: searchResults1 } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'énorme',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(searchResults1).to.have.length(1);
+ expect(searchResults1.map(doc => doc.id)).to.eql(['doc_1']);
+
+ const { documents: searchResults2 } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'c\'est',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(searchResults2).to.have.length(1);
+ expect(searchResults2.map(doc => doc.id)).to.eql(['doc_1']);
+ });
+
+ describe('search query can have filters', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Invoice cloudflare', originalName: 'document-1.pdf', content: 'Cloudflare invoice, hosting 5€', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Invoice smartphone', originalName: 'document-1.pdf', content: 'The smartphone invoice', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Car invoice', originalName: 'document-1.pdf', content: 'Your brand new car invoice, insurance attached', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ { id: 'doc_4', organizationId: 'org_1', name: 'Car insurance', originalName: 'document-2.pdf', content: 'Your car insurance contract', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash4', isDeleted: false },
+ { id: 'doc_5', organizationId: 'org_1', name: 'Meeting notes', originalName: 'document-3.pdf', content: 'Notes from the meeting about the new project', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash5', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ tags: [
+ { name: 'invoice', organizationId: 'org_1', id: 'tag_1', color: '#ff0000' },
+ { name: 'car', organizationId: 'org_1', id: 'tag_2', color: '#00ff00' },
+ ],
+ documents,
+ documentsTags: [
+ { documentId: 'doc_1', tagId: 'tag_1' },
+ { documentId: 'doc_2', tagId: 'tag_1' },
+ { documentId: 'doc_3', tagId: 'tag_1' },
+ { documentId: 'doc_3', tagId: 'tag_2' },
+ { documentId: 'doc_4', tagId: 'tag_2' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const searches = [
+ {
+ searchQuery: 'invoice',
+ expectedDocumentsIds: ['doc_1', 'doc_2', 'doc_3'],
+ },
+ {
+ searchQuery: 'invoice cloudflare',
+ expectedDocumentsIds: ['doc_1'],
+ },
+ {
+ searchQuery: 'tag:invoice',
+ expectedDocumentsIds: ['doc_1', 'doc_2', 'doc_3'],
+ },
+ {
+ searchQuery: 'tag:car tag:invoice',
+ expectedDocumentsIds: ['doc_3'],
+ },
+ {
+ searchQuery: 'tag:car NOT contract',
+ expectedDocumentsIds: ['doc_3'],
+ },
+ {
+ searchQuery: 'name:insurance',
+ expectedDocumentsIds: ['doc_4'],
+ },
+ {
+ searchQuery: 'name:invoice tag:invoice smartphone',
+ expectedDocumentsIds: ['doc_2'],
+ },
+ ];
+
+ for (const { searchQuery, expectedDocumentsIds } of searches) {
+ test(`search query: "${searchQuery}"`, async () => {
+ const { documents } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery,
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(documents.map(doc => doc.id).toSorted()).to.eql(expectedDocumentsIds.toSorted());
+ });
+ }
+ });
+
+ test('enforces organization isolation to prevent searching documents from other organizations', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Organization 1 Secret Document', originalName: 'secret-org1.pdf', content: 'confidential data for org 1', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Public Information', originalName: 'public.pdf', content: 'public data', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_2', name: 'Organization 2 Secret Document', originalName: 'secret-org2.pdf', content: 'confidential data for org 2', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ { id: 'doc_4', organizationId: 'org_2', name: 'Another Confidential File', originalName: 'confidential.pdf', content: 'more confidential information', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash4', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [
+ { id: 'org_1', name: 'Organization 1' },
+ { id: 'org_2', name: 'Organization 2' },
+ ],
+ documents,
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ // Index all documents from both organizations
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ // Search in org_1 with a term that exists in both organizations
+ const { documents: org1Results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'confidential',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ // Should only return documents from org_1, not org_2
+ expect(org1Results).to.have.length(1);
+ expect(org1Results.map(doc => doc.id)).to.eql(['doc_1']);
+ expect(org1Results.every(doc => doc.organizationId === 'org_1')).to.eql(true);
+
+ // Search in org_2 with the same term
+ const { documents: org2Results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_2',
+ searchQuery: 'confidential',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ // Should only return documents from org_2, not org_1
+ expect(org2Results).to.have.length(2);
+ expect(org2Results.map(doc => doc.id).toSorted()).to.eql(['doc_3', 'doc_4']);
+ expect(org2Results.every(doc => doc.organizationId === 'org_2')).to.eql(true);
+
+ // Search for organization-specific content should not leak across organizations
+ const { documents: org1SpecificSearch } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'Organization 2',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ // Even though "Organization 2" appears in org_2's documents, org_1 search should return nothing
+ expect(org1SpecificSearch).to.have.length(0);
});
});
describe('indexDocument', () => {
test('adds a document to the FTS index and makes it searchable', async () => {
const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
});
const documentsSearchRepository = createDocumentSearchRepository({ db });
// Insert a document in the documents table (no automatic FTS indexing after migration)
await db.insert(documentsTable).values({
- id: 'doc-1',
- organizationId: 'organization-1',
+ id: 'doc_1',
+ organizationId: 'org_1',
name: 'New Document',
originalName: 'new-doc.pdf',
content: 'searchable content here',
@@ -58,10 +234,10 @@ describe('database-fts5 repository', () => {
// Manually index the document to FTS
await documentsSearchRepository.indexDocument({
document: {
- id: 'doc-1',
+ id: 'doc_1',
name: 'New Document',
isDeleted: false,
- organizationId: 'organization-1',
+ organizationId: 'org_1',
originalName: 'new-doc.pdf',
content: 'searchable content here',
},
@@ -69,29 +245,29 @@ describe('database-fts5 repository', () => {
// Verify document is searchable
const { documents } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'searchable',
pageIndex: 0,
pageSize: 10,
});
expect(documents).to.have.length(1);
- expect(documents[0]?.id).to.equal('doc-1');
+ expect(documents[0]?.id).to.equal('doc_1');
});
});
describe('updateDocument', () => {
test('updates document fields in the FTS index to reflect changes in search results', async () => {
const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
});
const documentsSearchRepository = createDocumentSearchRepository({ db });
// Insert document and manually index it with original content
await db.insert(documentsTable).values({
- id: 'doc-1',
- organizationId: 'organization-1',
+ id: 'doc_1',
+ organizationId: 'org_1',
name: 'Original Name',
originalName: 'original.pdf',
content: 'original content',
@@ -102,18 +278,18 @@ describe('database-fts5 repository', () => {
await documentsSearchRepository.indexDocument({
document: {
- id: 'doc-1',
+ id: 'doc_1',
name: 'Original Name',
originalName: 'original.pdf',
content: 'original content',
isDeleted: false,
- organizationId: 'organization-1',
+ organizationId: 'org_1',
},
});
// Update the FTS index with new content
await documentsSearchRepository.updateDocument({
- documentId: 'doc-1',
+ documentId: 'doc_1',
document: {
name: 'Updated Name',
originalName: 'updated.pdf',
@@ -122,14 +298,14 @@ describe('database-fts5 repository', () => {
});
const resultsWithOldKeyword = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'original',
pageIndex: 0,
pageSize: 10,
});
const resultsWithNewKeyword = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'updated',
pageIndex: 0,
pageSize: 10,
@@ -137,14 +313,14 @@ describe('database-fts5 repository', () => {
expect(resultsWithOldKeyword.documents).to.have.length(0);
expect(resultsWithNewKeyword.documents).to.have.length(1);
- expect(resultsWithNewKeyword.documents[0]?.id).to.equal('doc-1');
+ expect(resultsWithNewKeyword.documents[0]?.id).to.equal('doc_1');
});
});
describe('deleteDocument', () => {
test('removes a document from the FTS index and makes it unsearchable', async () => {
const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
});
const documentsSearchRepository = createDocumentSearchRepository({ db });
@@ -152,8 +328,8 @@ describe('database-fts5 repository', () => {
// Insert documents and manually index them
await db.insert(documentsTable).values([
{
- id: 'doc-1',
- organizationId: 'organization-1',
+ id: 'doc_1',
+ organizationId: 'org_1',
name: 'Document to Delete',
originalName: 'delete-me.pdf',
content: 'this will be deleted',
@@ -162,8 +338,8 @@ describe('database-fts5 repository', () => {
originalSha256Hash: 'hash1',
},
{
- id: 'doc-2',
- organizationId: 'organization-1',
+ id: 'doc_2',
+ organizationId: 'org_1',
name: 'Document to Keep',
originalName: 'keep-me.pdf',
content: 'this will stay',
@@ -175,28 +351,28 @@ describe('database-fts5 repository', () => {
await documentsSearchRepository.indexDocument({
document: {
- id: 'doc-1',
+ id: 'doc_1',
name: 'Document to Delete',
originalName: 'delete-me.pdf',
content: 'this will be deleted',
isDeleted: false,
- organizationId: 'organization-1',
+ organizationId: 'org_1',
},
});
await documentsSearchRepository.indexDocument({
document: {
- id: 'doc-2',
+ id: 'doc_2',
name: 'Document to Keep',
originalName: 'keep-me.pdf',
content: 'this will stay',
isDeleted: false,
- organizationId: 'organization-1',
+ organizationId: 'org_1',
},
});
const beforeDelete = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'deleted',
pageIndex: 0,
pageSize: 10,
@@ -204,10 +380,10 @@ describe('database-fts5 repository', () => {
expect(beforeDelete.documents).to.have.length(1);
- await documentsSearchRepository.deleteDocument({ documentId: 'doc-1' });
+ await documentsSearchRepository.deleteDocument({ documentId: 'doc_1' });
const afterDelete = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'organization-1',
+ organizationId: 'org_1',
searchQuery: 'deleted',
pageIndex: 0,
pageSize: 10,
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 6f39c06c..60f3013d 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
@@ -1,10 +1,10 @@
import type { Database } from '../../../app/database/database.types';
import type { DocumentSearchableData } from '../document-search.types';
import { injectArguments } from '@corentinth/chisels';
-import { and, eq, getTableColumns, sql } from 'drizzle-orm';
+import { asc, eq } from 'drizzle-orm';
import { omitUndefined } from '../../../shared/utils';
import { documentsTable } from '../../documents.table';
-import { createFts5DocumentSearchQuery } from './database-fts5.repository.models';
+import { makeSearchWhereClause } from './database-fts5.repository.models';
import { documentsFtsTable } from './database-fts5.tables';
export type DocumentSearchRepository = ReturnType<typeof createDocumentSearchRepository>;
@@ -19,23 +19,23 @@ export function createDocumentSearchRepository({ db }: { db: Database }) {
}
async function searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, db }: { organizationId: string; searchQuery: string; pageIndex: number; pageSize: number; db: Database }) {
- const { query: formattedSearchQuery } = createFts5DocumentSearchQuery({ organizationId, searchQuery });
+ const { searchWhereClause } = makeSearchWhereClause({ organizationId, query: searchQuery, db });
- const documents = await db.select(getTableColumns(documentsTable))
+ const query = db.selectDistinct({
+ id: documentsTable.id,
+ organizationId: documentsTable.organizationId,
+ name: documentsTable.name,
+ })
.from(documentsTable)
- .innerJoin(
- documentsFtsTable,
- eq(documentsFtsTable.documentId, documentsTable.id),
- )
- .where(and(
- eq(documentsFtsTable.organizationId, organizationId),
- eq(documentsTable.isDeleted, false),
- eq(documentsFtsTable, formattedSearchQuery), // Match and eq works the same for FTS5 virtual tables
- ))
- .orderBy(sql`rank`)
+ .where(searchWhereClause)
+ .orderBy(asc(documentsTable.createdAt))
.limit(pageSize)
.offset(pageIndex * pageSize);
+ // console.log(query.toSQL());
+
+ const documents = await query;
+
return { documents };
}
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
new file mode 100644
index 00000000..99314729
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from 'vitest';
+import { formatFts5QueryValue } from './query-builder.models';
+
+describe('query-builder models', () => {
+ describe('formatFts5QueryValue', () => {
+ test('for a standard query, the organization id is included for performance and matching is done on name and content columns by default', () => {
+ expect(
+ formatFts5QueryValue({
+ value: 'foobar',
+ organizationId: 'org_1',
+ }),
+ ).to.eql({
+ queryString: 'organization_id:"org_1" {name content}:"foobar"*',
+ });
+ });
+
+ test('the matching columns can be customized', () => {
+ expect(
+ formatFts5QueryValue({
+ value: 'foobar',
+ organizationId: 'org_1',
+ matchingColumns: ['name'],
+ }),
+ ).to.eql({
+ queryString: 'organization_id:"org_1" {name}:"foobar"*',
+ });
+ });
+
+ test('if no matching columns are provided, all columns are searched', () => {
+ expect(
+ formatFts5QueryValue({
+ value: 'foobar',
+ organizationId: 'org_1',
+ matchingColumns: [],
+ }),
+ ).to.eql({
+ queryString: 'organization_id:"org_1" "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
new file mode 100644
index 00000000..ae9326ee
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.models.ts
@@ -0,0 +1,38 @@
+import { documentsFtsTable } from '../database-fts5.tables';
+
+function joinColumnNames(columns: string[]): string {
+ return columns.join(' ');
+}
+
+export function formatFts5QueryValue({
+ value,
+ organizationId,
+ matchingColumns = [
+ documentsFtsTable.name.name,
+ documentsFtsTable.content.name,
+ ],
+}: {
+ value: string;
+ 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}"*`,
+ ].join(' ');
+
+ return { queryString };
+}
+
+export function createUnsupportedOperatorIssue({ operator, field }: { operator: string; field: string }) {
+ return {
+ message: `Unsupported operator "${operator}" for ${field} filter`,
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ };
+}
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
new file mode 100644
index 00000000..d5adc9c9
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.test.ts
@@ -0,0 +1,354 @@
+import type { SQL } from 'drizzle-orm';
+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../../../app/database/database.test-utils';
+import { handleAndExpression, handleContentFilter, handleEmptyExpression, handleNameFilter, handleNotExpression, handleOrExpression, handleTextExpression, handleUnsupportedExpression } from './query-builder';
+
+describe('query-builder', async () => {
+ const { db } = await createInMemoryDatabase();
+ const sqliteDialect = new SQLiteSyncDialect();
+ const getSqlString = (query?: SQL) => {
+ if (!query) {
+ return { sql: '', params: [] };
+ }
+
+ const { sql, params } = sqliteDialect.sqlToQuery(query);
+ return { sql, params };
+ };
+
+ describe('handleNameFilter', () => {
+ test('builds a fts5 scoped on organization id and name column', () => {
+ const { sqlQuery, issues } = handleNameFilter({
+ expression: { type: 'filter', field: 'name', value: 'important', operator: '=' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {name}:"important"*'],
+ });
+ });
+
+ test('builds a fts5 scoped on organization id and name column with special characters escaped', () => {
+ const { sqlQuery, issues } = handleNameFilter({
+ expression: { type: 'filter', field: 'name', value: 'important (draft)', operator: '=' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {name}:"important (draft)"*'],
+ });
+ });
+
+ test('just the equality operator is supported ("=") for name filters, other operators return an issue and a no-op SQL query that evaluates to false', () => {
+ const { sqlQuery, issues } = handleNameFilter({
+ expression: { type: 'filter', field: 'name', value: 'important', operator: '>' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for name filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+
+ expect(getSqlString(sqlQuery)).to.eql({ sql: `0`, params: [] });
+ });
+ });
+
+ describe('handleContentFilter', () => {
+ test('builds a fts5 scoped on organization id and content column', () => {
+ const { sqlQuery, issues } = handleContentFilter({
+ expression: { type: 'filter', field: 'content', value: 'confidential', operator: '=' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {content}:"confidential"*'],
+ });
+ });
+
+ test('builds a fts5 scoped on organization id and content column with special characters escaped', () => {
+ const { sqlQuery, issues } = handleContentFilter({
+ expression: { type: 'filter', field: 'content', value: 'confidential [v2]', operator: '=' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {content}:"confidential [v2]"*'],
+ });
+ });
+
+ test('just the equality operator is supported ("=") for content filters, other operators return an issue and a no-op SQL query that evaluates to false', () => {
+ const { sqlQuery, issues } = handleContentFilter({
+ expression: { type: 'filter', field: 'content', value: 'confidential', operator: '<' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator "<" for content filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+
+ expect(getSqlString(sqlQuery)).to.eql({ sql: `0`, params: [] });
+ });
+ });
+
+ describe('handleEmptyExpression', () => {
+ test('when the expression is empty, it returns a no-op SQL query that always evaluates to true', () => {
+ const { sqlQuery, issues } = handleEmptyExpression();
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `1`,
+ params: [],
+ });
+ });
+ });
+
+ describe('handleTextExpression', () => {
+ test('builds a fts5 query matching both name and content columns scoped on organization id', () => {
+ const { sqlQuery, issues } = handleTextExpression({
+ expression: { type: 'text', value: 'budget report' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {name content}:"budget report"*'],
+ });
+ });
+
+ test('handles special characters in text expression (quotes are stripped by the formatter)', () => {
+ const { sqlQuery, issues } = handleTextExpression({
+ expression: { type: 'text', value: 'Q3 (final)' },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {name content}:"Q3 (final)"*'],
+ });
+ });
+ });
+
+ describe('handleAndExpression', () => {
+ test('combines multiple expressions with AND logic', () => {
+ const { sqlQuery, issues } = handleAndExpression({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'invoice' },
+ { type: 'filter', field: 'name', value: 'Q3', operator: '=' },
+ ],
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `(\"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"*',
+ ],
+ });
+ });
+
+ test('collects issues from all sub-expressions when combining with AND', () => {
+ const { sqlQuery, issues } = handleAndExpression({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'filter', field: 'name', value: 'important', operator: '>' },
+ { type: 'filter', field: 'content', value: 'secret', operator: '<' },
+ ],
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([
+ {
+ message: 'Unsupported operator ">" for name filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ },
+ {
+ message: 'Unsupported operator "<" for content filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ },
+ ]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `(0 and 0)`,
+ params: [],
+ });
+ });
+ });
+
+ describe('handleOrExpression', () => {
+ test('combines multiple expressions with OR logic', () => {
+ const { sqlQuery, issues } = handleOrExpression({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'invoice' },
+ { type: 'text', value: 'receipt' },
+ ],
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `(\"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?) or \"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 content}:"receipt"*',
+ ],
+ });
+ });
+
+ test('collects issues from all sub-expressions when combining with OR', () => {
+ const { sqlQuery, issues } = handleOrExpression({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'filter', field: 'name', value: 'test', operator: '>' },
+ { type: 'filter', field: 'content', value: 'data', operator: '>=' },
+ ],
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([
+ {
+ message: 'Unsupported operator ">" for name filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ },
+ {
+ message: 'Unsupported operator ">=" for content filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ },
+ ]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `(0 or 0)`,
+ params: [],
+ });
+ });
+ });
+
+ describe('handleNotExpression', () => {
+ test('inverts a valid expression with NOT logic', () => {
+ const { sqlQuery, issues } = handleNotExpression({
+ expression: {
+ type: 'not',
+ operand: { type: 'text', value: 'spam' },
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `not \"documents\".\"id\" in (select distinct \"document_id\" from \"documents_fts\" where \"documents_fts\" = ?)`,
+ params: ['organization_id:"org_1" {name content}:"spam"*'],
+ });
+ });
+
+ test('does not treat empty operand as error because empty always matches truthy in sql', () => {
+ const { sqlQuery, issues } = handleNotExpression({
+ expression: {
+ type: 'not',
+ operand: { type: 'empty' },
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `not 1`,
+ params: [],
+ });
+ });
+
+ test('propagates issues from nested expression when negating', () => {
+ const { sqlQuery, issues } = handleNotExpression({
+ expression: {
+ type: 'not',
+ operand: { type: 'filter', field: 'name', value: 'test', operator: '<' },
+ },
+ organizationId: 'org_1',
+ db,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator "<" for name filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `not 0`,
+ params: [],
+ });
+ });
+ });
+
+ describe('handleUnsupportedExpression', () => {
+ test('returns error for unsupported expression types', () => {
+ const { sqlQuery, issues } = handleUnsupportedExpression();
+
+ expect(issues).to.eql([{
+ message: 'Unsupported expression type',
+ code: 'UNSUPPORTED_EXPRESSION_TYPE',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: `0`, params: [] });
+ });
+
+ test('returns a no-op SQL query that always evaluates to false', () => {
+ const { sqlQuery, issues } = handleUnsupportedExpression();
+
+ expect(issues).to.eql([{
+ message: 'Unsupported expression type',
+ code: 'UNSUPPORTED_EXPRESSION_TYPE',
+ }]);
+
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `0`,
+ params: [],
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts
new file mode 100644
index 00000000..27adde7c
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts
@@ -0,0 +1,183 @@
+import type { AndExpression, Expression, FilterExpression, NotExpression, OrExpression, TextExpression } from '@papra/search-parser';
+import type { Database } from '../../../../app/database/database.types';
+import type { QueryResult } from './query-builder.types';
+import { and, eq, inArray, not, or, sql } from 'drizzle-orm';
+import { documentsTagsTable, tagsTable } from '../../../../tags/tags.table';
+import { documentsTable } from '../../../documents.table';
+import { documentsFtsTable } from '../database-fts5.tables';
+import { createUnsupportedOperatorIssue, formatFts5QueryValue } from './query-builder.models';
+
+export function handleEmptyExpression(): QueryResult {
+ return {
+ sqlQuery: sql`1`,
+ issues: [],
+ };
+}
+
+export function handleNameFilter({ expression, organizationId, db }: { expression: FilterExpression; organizationId: string; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return {
+ sqlQuery: sql`0`,
+ issues: [createUnsupportedOperatorIssue({ operator, field })],
+ };
+ }
+
+ const { queryString } = formatFts5QueryValue({
+ value,
+ organizationId,
+ matchingColumns: [
+ documentsFtsTable.name.name,
+ ],
+ });
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.selectDistinct({ documentId: documentsFtsTable.documentId }).from(documentsFtsTable).where(eq(documentsFtsTable, queryString)),
+ ),
+ issues: [],
+ };
+}
+
+export function handleContentFilter({ expression, organizationId, db }: { expression: FilterExpression; organizationId: string; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return {
+ sqlQuery: sql`0`,
+ issues: [createUnsupportedOperatorIssue({ operator, field })],
+ };
+ }
+
+ const { queryString } = formatFts5QueryValue({
+ value,
+ organizationId,
+ matchingColumns: [
+ documentsFtsTable.content.name,
+ ],
+ });
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.selectDistinct({ documentId: documentsFtsTable.documentId }).from(documentsFtsTable).where(eq(documentsFtsTable, queryString)),
+ ),
+ issues: [],
+ };
+}
+
+export function handleTextExpression({ expression, organizationId, db }: { expression: TextExpression; organizationId: string; db: Database }): QueryResult {
+ const { value } = expression;
+ const { queryString } = formatFts5QueryValue({
+ value,
+ organizationId,
+ matchingColumns: [
+ documentsFtsTable.name.name,
+ documentsFtsTable.content.name,
+ ],
+ });
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.selectDistinct({ documentId: documentsFtsTable.documentId }).from(documentsFtsTable).where(eq(documentsFtsTable, queryString)),
+ ),
+ issues: [],
+ };
+}
+
+export function handleAndExpression({ expression, organizationId, db }: { expression: AndExpression; organizationId: string; db: Database }): QueryResult {
+ const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db }));
+
+ return {
+ sqlQuery: and(...subQueries.map(sq => sq.sqlQuery)),
+ issues: subQueries.flatMap(sq => sq.issues),
+ };
+}
+
+export function handleOrExpression({ expression, organizationId, db }: { expression: OrExpression; organizationId: string; db: Database }): QueryResult {
+ const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db }));
+
+ return {
+ sqlQuery: or(...subQueries.map(sq => sq.sqlQuery)),
+ issues: subQueries.flatMap(sq => sq.issues),
+ };
+}
+
+export function handleNotExpression({ expression, organizationId, db }: { expression: NotExpression; organizationId: string; db: Database }): QueryResult {
+ const subQuery = buildQueryFromExpression({ expression: expression.operand, organizationId, db });
+
+ if (!subQuery.sqlQuery) {
+ // Should not happen, but just for type safety
+ return {
+ sqlQuery: sql`0`,
+ issues: [
+ {
+ message: 'NOT operator requires a valid operand',
+ code: 'EMPTY_NOT_OPERAND',
+ },
+ ...subQuery.issues,
+ ],
+ };
+ }
+
+ return {
+ sqlQuery: not(subQuery.sqlQuery),
+ issues: subQuery.issues,
+ };
+}
+
+export function handleTagFilter({ expression, organizationId, db }: { expression: FilterExpression; organizationId: string; db: Database }): QueryResult {
+ const { value } = expression;
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.selectDistinct({ documentId: documentsTagsTable.documentId })
+ .from(documentsTagsTable)
+ .innerJoin(tagsTable, eq(documentsTagsTable.tagId, tagsTable.id))
+ .where(and(
+ // Ensure tag belongs to the same organization + helps performance as there is an index on (organizationId + name)
+ eq(tagsTable.organizationId, organizationId),
+ or(
+ eq(tagsTable.name, value),
+ eq(tagsTable.id, value),
+ ),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+export function handleUnsupportedExpression(): QueryResult {
+ return {
+ sqlQuery: sql`0`,
+ issues: [
+ {
+ message: 'Unsupported expression type',
+ code: 'UNSUPPORTED_EXPRESSION_TYPE',
+ },
+ ],
+ };
+}
+
+export function buildQueryFromExpression({ expression, organizationId, db }: { expression: Expression; organizationId: string; db: Database }): QueryResult {
+ // I usually prefer a LUT, but for type narrowing, switch is more convenient and avoids casting
+ switch (expression.type) {
+ case 'empty': return handleEmptyExpression();
+ case 'text': return handleTextExpression({ expression, organizationId, db });
+ case 'and': return handleAndExpression({ expression, organizationId, db });
+ case 'or': return handleOrExpression({ expression, organizationId, db });
+ case 'not': return handleNotExpression({ expression, organizationId, db });
+ case 'filter':
+ switch (expression.field) {
+ case 'tag': return handleTagFilter({ expression, organizationId, db });
+ case 'name': return handleNameFilter({ expression, organizationId, db });
+ case 'content': return handleContentFilter({ expression, organizationId, db });
+ default: return handleUnsupportedExpression();
+ }
+ default: return handleUnsupportedExpression();
+ }
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.types.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.types.ts
new file mode 100644
index 00000000..2b8cdebe
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.types.ts
@@ -0,0 +1,6 @@
+import type { SQL } from 'drizzle-orm';
+
+export type QueryResult = {
+ sqlQuery?: SQL;
+ issues: { message: string; code: string }[];
+};
diff --git a/packages/search-parser/src/index.ts b/packages/search-parser/src/index.ts
index 7c0763a6..dced5f5b 100644
--- a/packages/search-parser/src/index.ts
+++ b/packages/search-parser/src/index.ts
@@ -2,6 +2,10 @@ export {
ERROR_CODES,
} from './errors';
+export {
+ simplifyExpression,
+} from './optimization';
+
export {
parseSearchQuery,
} from './parser';
diff --git a/packages/search-parser/src/optimization.test.ts b/packages/search-parser/src/optimization.test.ts
new file mode 100644
index 00000000..76ff4b2b
--- /dev/null
+++ b/packages/search-parser/src/optimization.test.ts
@@ -0,0 +1,662 @@
+import type { Expression } from './parser.types';
+import { describe, expect, test } from 'vitest';
+import { simplifyExpression } from './optimization';
+
+describe('simplifyExpression', () => {
+ describe('when handling leaf nodes', () => {
+ test('returns empty expression unchanged', () => {
+ const expression: Expression = { type: 'empty' };
+ expect(simplifyExpression({ expression })).toEqual({ expression });
+ });
+
+ test('returns text expression unchanged', () => {
+ const expression: Expression = { type: 'text', value: 'hello' };
+ expect(simplifyExpression({ expression })).toEqual({ expression });
+ });
+
+ test('returns filter expression unchanged', () => {
+ const expression: Expression = {
+ type: 'filter',
+ field: 'tag',
+ operator: '=',
+ value: 'invoice',
+ };
+ expect(simplifyExpression({ expression })).toEqual({ expression });
+ });
+ });
+
+ describe('when simplifying single-child AND/OR expressions', () => {
+ test('simplifies AND with single child to that child', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [{ type: 'text', value: 'hello' }],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'text', value: 'hello' },
+ });
+ });
+
+ test('simplifies OR with single child to that child', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [{ type: 'filter', field: 'tag', operator: '=', value: 'invoice' }],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ });
+ });
+
+ test('simplifies nested single-child expressions', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ {
+ type: 'or',
+ operands: [{ type: 'text', value: 'hello' }],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'text', value: 'hello' },
+ });
+ });
+ });
+
+ describe('when eliminating double negation', () => {
+ test('simplifies NOT(NOT(A)) to A', () => {
+ const expression: Expression = {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'hello' },
+ },
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'text', value: 'hello' },
+ });
+ });
+
+ test('simplifies NOT(NOT(NOT(NOT(A)))) to A', () => {
+ const expression: Expression = {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'hello' },
+ },
+ },
+ },
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'text', value: 'hello' },
+ });
+ });
+
+ test('simplifies NOT(NOT(NOT(A))) to NOT(A)', () => {
+ const expression: Expression = {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'hello' },
+ },
+ },
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'not',
+ operand: { type: 'text', value: 'hello' },
+ },
+ });
+ });
+ });
+
+ describe('when flattening nested AND/OR expressions', () => {
+ test('flattens nested AND expressions', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ });
+ });
+
+ test('flattens nested OR expressions', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ });
+ });
+
+ test('flattens deeply nested expressions', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ },
+ { type: 'text', value: 'd' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ { type: 'text', value: 'd' },
+ ],
+ },
+ });
+ });
+
+ test('does not flatten AND inside OR', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ },
+ });
+ });
+
+ test('does not flatten OR inside AND', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ ],
+ },
+ });
+ });
+ });
+
+ describe('when removing empty expressions', () => {
+ test('removes empty from AND operands', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'empty' },
+ { type: 'text', value: 'b' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ });
+ });
+
+ test('removes empty from OR operands', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ { type: 'empty' },
+ { type: 'text', value: 'a' },
+ { type: 'empty' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'text', value: 'a' },
+ });
+ });
+
+ test('simplifies NOT(empty) to empty', () => {
+ const expression: Expression = {
+ type: 'not',
+ operand: { type: 'empty' },
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'empty' },
+ });
+ });
+ });
+
+ describe('when applying identity laws', () => {
+ test('simplifies AND() to empty', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'empty' },
+ });
+ });
+
+ test('simplifies OR() to empty', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'empty' },
+ });
+ });
+
+ test('simplifies AND(empty, empty) to empty', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [{ type: 'empty' }, { type: 'empty' }],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: { type: 'empty' },
+ });
+ });
+ });
+
+ describe('when removing duplicates', () => {
+ test('removes duplicate text expressions from AND', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'hello' },
+ { type: 'text', value: 'world' },
+ { type: 'text', value: 'hello' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'hello' },
+ { type: 'text', value: 'world' },
+ ],
+ },
+ });
+ });
+
+ test('removes duplicate filter expressions from OR', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '=', value: 'receipt' },
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '=', value: 'receipt' },
+ ],
+ },
+ });
+ });
+
+ test('removes duplicate complex nested expressions', () => {
+ const duplicateExpr: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ };
+
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ duplicateExpr,
+ { type: 'text', value: 'c' },
+ duplicateExpr,
+ ],
+ };
+
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ });
+ });
+
+ test('respects order when deduplicating - keeps first occurrence', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'c' },
+ { type: 'text', value: 'b' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'c' },
+ ],
+ },
+ });
+ });
+
+ test('treats AND(A, B) and AND(B, A) as different (order matters)', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'a' },
+ ],
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'b' },
+ { type: 'text', value: 'a' },
+ ],
+ },
+ ],
+ },
+ });
+ });
+ });
+
+ describe('when combining multiple optimizations', () => {
+ test('applies all optimizations in sequence', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'a' },
+ ],
+ },
+ { type: 'empty' },
+ {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'b' },
+ },
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ });
+ });
+
+ test('handles complex nested structure with all optimization types', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'x' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'x' },
+ { type: 'empty' },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: {
+ type: 'or',
+ operands: [{ type: 'text', value: 'y' }],
+ },
+ },
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'text', value: 'x' },
+ { type: 'text', value: 'y' },
+ ],
+ },
+ });
+ });
+
+ test('simplifies all duplicates after flattening', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ { type: 'text', value: 'b' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'a' },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ });
+ });
+ });
+
+ describe('when handling edge cases', () => {
+ test('preserves NOT expressions that cannot be simplified', () => {
+ const expression: Expression = {
+ type: 'not',
+ operand: { type: 'text', value: 'hello' },
+ };
+ expect(simplifyExpression({ expression })).toEqual({ expression });
+ });
+
+ test('handles expressions with different filter operators', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ { type: 'filter', field: 'createdAt', operator: '>', value: '2024-01-01' },
+ { type: 'filter', field: 'createdAt', operator: '<', value: '2024-12-31' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({ expression });
+ });
+
+ test('treats same field with different operators as different', () => {
+ const expression: Expression = {
+ type: 'or',
+ operands: [
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '>', value: 'invoice' },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'or',
+ operands: [
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '>', value: 'invoice' },
+ ],
+ },
+ });
+ });
+
+ test('handles deeply nested NOT expressions correctly', () => {
+ const expression: Expression = {
+ type: 'and',
+ operands: [
+ {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'a' },
+ },
+ },
+ },
+ {
+ type: 'not',
+ operand: {
+ type: 'not',
+ operand: { type: 'text', value: 'b' },
+ },
+ },
+ ],
+ };
+ expect(simplifyExpression({ expression })).toEqual({
+ expression: {
+ type: 'and',
+ operands: [
+ { type: 'not', operand: { type: 'text', value: 'a' } },
+ { type: 'text', value: 'b' },
+ ],
+ },
+ });
+ });
+ });
+});
diff --git a/packages/search-parser/src/optimization.ts b/packages/search-parser/src/optimization.ts
new file mode 100644
index 00000000..eb6f1864
--- /dev/null
+++ b/packages/search-parser/src/optimization.ts
@@ -0,0 +1,165 @@
+import type { AndExpression, Expression, OrExpression } from './parser.types';
+
+/**
+ * Simplifies an expression tree by applying optimization rules.
+ * - AND/OR expressions with a single child are replaced by that child.
+ * - NOT expressions with a NOT child are replaced by the grandchild (double negation).
+ * - Nested AND/OR expressions are flattened.
+ * - Redundant expressions are removed (duplicates, empty expressions).
+ * - Empty AND/OR expressions are converted to 'empty'.
+ */
+export function simplifyExpression({ expression }: { expression: Expression }): { expression: Expression } {
+ return { expression: simplify(expression) };
+}
+
+/**
+ * Recursively simplifies an expression tree using post-order traversal.
+ * Children are optimized before their parents.
+ */
+function simplify(expression: Expression): Expression {
+ // Base cases: leaf nodes that can't be simplified further
+ if (expression.type === 'empty' || expression.type === 'text' || expression.type === 'filter') {
+ return expression;
+ }
+
+ // Recursive case: NOT expression
+ if (expression.type === 'not') {
+ const simplifiedOperand = simplify(expression.operand);
+
+ // Double negation elimination: NOT(NOT(A)) -> A
+ if (simplifiedOperand.type === 'not') {
+ return simplifiedOperand.operand;
+ }
+
+ // Empty propagation: NOT(empty) -> empty
+ if (simplifiedOperand.type === 'empty') {
+ return { type: 'empty' };
+ }
+
+ return { type: 'not', operand: simplifiedOperand };
+ }
+
+ // Recursive case: AND/OR expressions
+ if (expression.type === 'and' || expression.type === 'or') {
+ // Step 1: Simplify all operands recursively
+ let simplifiedOperands = expression.operands.map(simplify);
+
+ // Step 2: Flatten nested expressions of the same type
+ simplifiedOperands = flattenOperands(expression.type, simplifiedOperands);
+
+ // Step 3: Remove empty expressions
+ simplifiedOperands = simplifiedOperands.filter(op => op.type !== 'empty');
+
+ // Step 4: Remove duplicates (order-preserving)
+ simplifiedOperands = deduplicateOperands(simplifiedOperands);
+
+ // Step 5: Apply identity laws
+ // Empty: AND() -> empty, OR() -> empty
+ if (simplifiedOperands.length === 0) {
+ return { type: 'empty' };
+ }
+
+ // Single child: AND(A) -> A, OR(A) -> A
+ if (simplifiedOperands.length === 1) {
+ return simplifiedOperands[0]!;
+ }
+
+ // Return simplified AND/OR expression
+ return {
+ type: expression.type,
+ operands: simplifiedOperands,
+ } as AndExpression | OrExpression;
+ }
+
+ // This should never be reached if Expression type is exhaustive
+ return expression;
+}
+
+/**
+ * Flattens nested AND/OR expressions of the same type.
+ * Example: AND(A, AND(B, C)) -> AND(A, B, C)
+ */
+function flattenOperands(type: 'and' | 'or', operands: Expression[]): Expression[] {
+ const flattened: Expression[] = [];
+
+ for (const operand of operands) {
+ // If operand is same type (AND/OR), merge its children
+ if (operand.type === type) {
+ flattened.push(...operand.operands);
+ } else {
+ flattened.push(operand);
+ }
+ }
+
+ return flattened;
+}
+
+/**
+ * Removes duplicate operands while preserving order.
+ * Uses deep equality comparison.
+ */
+function deduplicateOperands(operands: Expression[]): Expression[] {
+ const deduplicated: Expression[] = [];
+
+ for (const operand of operands) {
+ // Only add if not already present
+ const isDuplicate = deduplicated.some(existing => expressionsEqual(existing, operand));
+ if (!isDuplicate) {
+ deduplicated.push(operand);
+ }
+ }
+
+ return deduplicated;
+}
+
+/**
+ * Deep equality comparison for expressions.
+ * Order-sensitive: AND(A, B) !== AND(B, A)
+ */
+function expressionsEqual(a: Expression, b: Expression): boolean {
+ // Different types are not equal
+ if (a.type !== b.type) {
+ return false;
+ }
+
+ // Empty expressions are always equal
+ if (a.type === 'empty') {
+ return true;
+ }
+
+ // Text expressions: compare values
+ if (a.type === 'text' && b.type === 'text') {
+ return a.value === b.value;
+ }
+
+ // Filter expressions: compare all fields
+ if (a.type === 'filter' && b.type === 'filter') {
+ return a.field === b.field
+ && a.operator === b.operator
+ && a.value === b.value;
+ }
+
+ // NOT expressions: compare operands
+ if (a.type === 'not' && b.type === 'not') {
+ return expressionsEqual(a.operand, b.operand);
+ }
+
+ // AND/OR expressions: compare operands arrays (order-sensitive)
+ if ((a.type === 'and' && b.type === 'and') || (a.type === 'or' && b.type === 'or')) {
+ if (a.operands.length !== b.operands.length) {
+ return false;
+ }
+
+ // Compare each operand in order
+ for (let i = 0; i < a.operands.length; i++) {
+ if (!expressionsEqual(a.operands[i]!, b.operands[i]!)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ // Fallback: not equal
+ return false;
+}
diff --git a/packages/search-parser/src/parser.test.ts b/packages/search-parser/src/parser.test.ts
index d4735767..955d9bae 100644
--- a/packages/search-parser/src/parser.test.ts
+++ b/packages/search-parser/src/parser.test.ts
@@ -686,4 +686,74 @@ describe('parseSearchQuery', () => {
});
});
});
+
+ describe('when using optimization', () => {
+ test('applies optimization when optimize flag is true', () => {
+ // Query that creates nested AND that can be flattened
+ const result = parseSearchQuery({
+ query: 'foo foo bar',
+ optimize: true,
+ });
+
+ // Should remove duplicate 'foo' through optimization
+ expect(result.expression).toEqual({
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'foo' },
+ { type: 'text', value: 'bar' },
+ ],
+ });
+ expect(result.issues).toEqual([]);
+ });
+
+ test('does not apply optimization when optimize flag is false', () => {
+ const result = parseSearchQuery({
+ query: 'foo foo bar',
+ optimize: false,
+ });
+
+ // Should keep duplicates without optimization
+ expect(result.expression).toEqual({
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'foo' },
+ { type: 'text', value: 'foo' },
+ { type: 'text', value: 'bar' },
+ ],
+ });
+ expect(result.issues).toEqual([]);
+ });
+
+ test('does not apply optimization by default', () => {
+ const result = parseSearchQuery({ query: 'foo foo bar' });
+
+ // Should keep duplicates without optimization (default behavior)
+ expect(result.expression).toEqual({
+ type: 'and',
+ operands: [
+ { type: 'text', value: 'foo' },
+ { type: 'text', value: 'foo' },
+ { type: 'text', value: 'bar' },
+ ],
+ });
+ expect(result.issues).toEqual([]);
+ });
+
+ test('applies optimization to complex queries', () => {
+ // Query with double negation and duplicates
+ const result = parseSearchQuery({
+ query: '(tag:invoice OR tag:invoice) AND NOT NOT tag:receipt',
+ optimize: true,
+ });
+
+ expect(result.expression).toEqual({
+ type: 'and',
+ operands: [
+ { type: 'filter', field: 'tag', operator: '=', value: 'invoice' },
+ { type: 'filter', field: 'tag', operator: '=', value: 'receipt' },
+ ],
+ });
+ expect(result.issues).toEqual([]);
+ });
+ });
});
diff --git a/packages/search-parser/src/parser.ts b/packages/search-parser/src/parser.ts
index 748f8a41..0043506a 100644
--- a/packages/search-parser/src/parser.ts
+++ b/packages/search-parser/src/parser.ts
@@ -1,6 +1,7 @@
import type { Expression, Issue, ParsedQuery } from './parser.types';
import type { Token } from './tokenizer';
import { ERROR_CODES } from './errors';
+import { simplifyExpression } from './optimization';
import { tokenize } from './tokenizer';
export function parseSearchQuery(
@@ -8,19 +9,32 @@ export function parseSearchQuery(
query,
maxDepth = 10,
maxTokens = 200,
+ optimize = false,
}: {
query: string;
maxDepth?: number;
maxTokens?: number;
+ optimize?: boolean;
},
): ParsedQuery {
const { tokens, issues: tokenizerIssues } = tokenize({ query, maxTokens });
const { expression, issues: parserIssues } = parseExpression({ tokens, maxDepth });
+ const issues = [...tokenizerIssues, ...parserIssues];
+
+ if (!optimize) {
+ return {
+ expression,
+ issues,
+ };
+ }
+
+ const { expression: optimizedExpression } = simplifyExpression({ expression });
+
return {
- expression,
- issues: [...tokenizerIssues, ...parserIssues],
+ expression: optimizedExpression,
+ issues,
};
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9b64094d..48f540c3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -449,6 +449,9 @@ importers:
'@papra/lecture':
specifier: workspace:*
version: link:../../packages/lecture
+ '@papra/search-parser':
+ specifier: workspace:*
+ version: link:../../packages/search-parser
'@papra/webhooks':
specifier: workspace:*
version: link:../../packages/webhooks
@@ -19943,7 +19946,7 @@ snapshots:
'@typescript-eslint/parser': 8.46.2([email protected]([email protected]))([email protected])
eslint: 9.39.1([email protected])
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
@@ -19972,7 +19975,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3([email protected])
@@ -19997,14 +20000,14 @@ snapshots:
dependencies:
eslint: 9.39.1([email protected])
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.46.2([email protected]([email protected]))([email protected])
eslint: 9.39.1([email protected])
eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -20067,7 +20070,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.1([email protected])
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3