From a8cb2858995001a8596c3a134885a8ae2a46c75a Mon Sep 17 00:00:00 2001 From: Helder Pereira Date: Sun, 29 Aug 2021 16:13:07 +0100 Subject: [PATCH] Improve search logic --- static/js/search.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/static/js/search.js b/static/js/search.js index 3f69c9cee9..82c906ec43 100644 --- a/static/js/search.js +++ b/static/js/search.js @@ -39,17 +39,27 @@ function initLunr() { /** * Trigger a search in lunr and transform the result * - * @param {String} query + * @param {String} term * @return {Array} results */ -function search(queryTerm) { +function search(term) { // Find the item in our index corresponding to the lunr one to have more info - var searchTerm = queryTerm.match(/\w+/g).map(word => word + '^100' + ' ' + word + '*^10' + ' ' + '*' + word + '^10' + ' ' + word + '~2^1').join(' '); - return lunrIndex.search(searchTerm).map(function(result) { - return { index: result.ref, matches: Object.keys(result.matchData.metadata) }; + // Remove Lunr special search characters: https://lunrjs.com/guides/searching.html + var searchTerm = lunr.tokenizer(term.replace(/[*:^~+-]/, ' ')).flatMap(token => searchPatterns(token.str)).join(' '); + return !searchTerm ? [] : lunrIndex.search(searchTerm).map(function(result) { + return { index: result.ref, matches: Object.keys(result.matchData.metadata) } }); } +function searchPatterns(word) { + return [ + word + '^100', + word + '*^10', + '*' + word + '^10', + word + '~' + Math.floor(word.length / 4) + '^1' // allow 1 in 4 letters to have a typo + ]; +} + // Let's get started initLunr(); $(function() {