2021-01-22 19:41:11 +02:00
|
|
|
import SearchEngine from './SearchEngine';
|
|
|
|
import Note from '../../models/Note';
|
2018-12-16 19:32:42 +02:00
|
|
|
|
2021-01-22 19:41:11 +02:00
|
|
|
export default class SearchEngineUtils {
|
|
|
|
static async notesForQuery(query: string, options: any = null) {
|
2019-02-24 14:24:55 +02:00
|
|
|
if (!options) options = {};
|
|
|
|
|
2020-04-18 13:45:54 +02:00
|
|
|
let searchType = SearchEngine.SEARCH_TYPE_FTS;
|
|
|
|
if (query.length && query[0] === '/') {
|
|
|
|
query = query.substr(1);
|
|
|
|
searchType = SearchEngine.SEARCH_TYPE_BASIC;
|
|
|
|
}
|
|
|
|
|
2020-09-15 15:01:07 +02:00
|
|
|
const results = await SearchEngine.instance().search(query, { searchType });
|
2021-01-22 19:41:11 +02:00
|
|
|
const noteIds = results.map((n: any) => n.id);
|
2018-12-16 19:32:42 +02:00
|
|
|
|
2019-02-24 14:37:37 +02:00
|
|
|
// We need at least the note ID to be able to sort them below so if not
|
|
|
|
// present in field list, add it.L Also remember it was auto-added so that
|
|
|
|
// it can be removed afterwards.
|
|
|
|
let idWasAutoAdded = false;
|
|
|
|
const fields = options.fields ? options.fields : Note.previewFields().slice();
|
|
|
|
if (fields.indexOf('id') < 0) {
|
|
|
|
fields.push('id');
|
|
|
|
idWasAutoAdded = true;
|
|
|
|
}
|
|
|
|
|
2020-04-18 13:45:54 +02:00
|
|
|
const previewOptions = Object.assign({}, {
|
|
|
|
order: [],
|
|
|
|
fields: fields,
|
|
|
|
conditions: [`id IN ("${noteIds.join('","')}")`],
|
|
|
|
}, options);
|
2018-12-16 19:32:42 +02:00
|
|
|
|
|
|
|
const notes = await Note.previews(null, previewOptions);
|
|
|
|
|
|
|
|
// By default, the notes will be returned in reverse order
|
|
|
|
// or maybe random order so sort them here in the correct order
|
|
|
|
// (search engine returns the results in order of relevance).
|
|
|
|
const sortedNotes = [];
|
|
|
|
for (let i = 0; i < notes.length; i++) {
|
|
|
|
const idx = noteIds.indexOf(notes[i].id);
|
|
|
|
sortedNotes[idx] = notes[i];
|
2019-02-24 14:37:37 +02:00
|
|
|
if (idWasAutoAdded) delete sortedNotes[idx].id;
|
2018-12-16 19:32:42 +02:00
|
|
|
}
|
|
|
|
|
2020-08-19 00:53:28 +02:00
|
|
|
|
|
|
|
// Note that when the search engine index is somehow corrupted, it might contain
|
|
|
|
// references to notes that don't exist. Not clear how it can happen, but anyway
|
|
|
|
// handle it here by checking if `user_updated_time` IS NOT NULL. Was causing this
|
|
|
|
// issue: https://discourse.joplinapp.org/t/how-to-recover-corrupted-database/9367
|
2020-08-08 01:13:21 +02:00
|
|
|
if (noteIds.length !== notes.length) {
|
|
|
|
// remove null objects
|
|
|
|
return sortedNotes.filter(n => n);
|
|
|
|
} else {
|
|
|
|
return sortedNotes;
|
|
|
|
}
|
|
|
|
|
2018-12-16 19:32:42 +02:00
|
|
|
}
|
|
|
|
}
|