Improve search logic

This commit is contained in:
Helder Pereira 2021-08-29 16:13:07 +01:00
parent 98ccdc2bd6
commit a8cb285899

View file

@ -39,17 +39,27 @@ function initLunr() {
/** /**
* Trigger a search in lunr and transform the result * Trigger a search in lunr and transform the result
* *
* @param {String} query * @param {String} term
* @return {Array} results * @return {Array} results
*/ */
function search(queryTerm) { function search(term) {
// Find the item in our index corresponding to the lunr one to have more info // 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(' '); // Remove Lunr special search characters: https://lunrjs.com/guides/searching.html
return lunrIndex.search(searchTerm).map(function(result) { var searchTerm = lunr.tokenizer(term.replace(/[*:^~+-]/, ' ')).flatMap(token => searchPatterns(token.str)).join(' ');
return { index: result.ref, matches: Object.keys(result.matchData.metadata) }; 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 // Let's get started
initLunr(); initLunr();
$(function() { $(function() {