From a69e020738d9f4cb04b04f4897d68e310d15eb82 Mon Sep 17 00:00:00 2001 From: Simon Cambier Date: Mon, 5 Dec 2022 12:59:53 +0100 Subject: [PATCH] Fixed order of operations: search > filter & sort > slice Also passing options.singleFilePath to search() for better perfs --- src/search/omnisearch.ts | 51 ++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/src/search/omnisearch.ts b/src/search/omnisearch.ts index b0872b0..ccbc971 100644 --- a/src/search/omnisearch.ts +++ b/src/search/omnisearch.ts @@ -151,7 +151,7 @@ export class Omnisearch { */ public async search( query: Query, - options: { prefixLength: number } + options: { prefixLength: number; singleFilePath?: string } ): Promise { if (query.isEmpty()) { this.previousResults = [] @@ -172,6 +172,10 @@ export class Omnisearch { }) if (!results.length) return this.previousResults + if (options.singleFilePath) { + return results.filter(r => r.id === options.singleFilePath) + } + // Hide or downrank files that are in Obsidian's excluded list if (settings.hideExcluded) { // Filter the files out @@ -194,6 +198,20 @@ export class Omnisearch { }) } + // Extract tags from the query + const tags = query.segments + .filter(s => s.value.startsWith('#')) + .map(s => s.value) + + // Put the results with tags on top + for (const tag of tags) { + for (const result of results) { + if ((result.tags ?? []).includes(tag)) { + result.score *= 100 + } + } + } + results = results.slice(0, 50) const documents = await Promise.all( @@ -266,14 +284,20 @@ export class Omnisearch { */ public async getSuggestions( query: Query, - options?: Partial<{ singleFilePath: string | null }> + options?: Partial<{ singleFilePath?: string }> ): Promise { // Get the raw results let results: SearchResult[] if (settings.simpleSearch) { - results = await this.search(query, { prefixLength: 1 }) + results = await this.search(query, { + prefixLength: 1, + singleFilePath: options?.singleFilePath, + }) } else { - results = await this.search(query, { prefixLength: 3 }) + results = await this.search(query, { + prefixLength: 3, + singleFilePath: options?.singleFilePath, + }) } // Extract tags from the query @@ -281,25 +305,6 @@ export class Omnisearch { .filter(s => s.value.startsWith('#')) .map(s => s.value) - // Either keep the 50 first results, - // or the one corresponding to `singleFile` - if (options?.singleFilePath) { - const result = results.find(r => r.id === options.singleFilePath) - if (result) results = [result] - else results = [] - } else { - results = results.slice(0, 50) - - // Put the results with tags on top - for (const tag of tags) { - for (const result of results) { - if ((result.tags ?? []).includes(tag)) { - result.score *= 100 - } - } - } - } - // TODO: this already called in search(), pass each document in its SearchResult instead? const documents = await Promise.all( results.map(async result => await cacheManager.getDocument(result.id))