Pre-process query:

- Search for terms in AND mode, per
  https://lunrjs.com/guides/searching.html#term-presence
- Discard non-alphanumeric characters from the search
- Better handling of contractions and searching for stop words
This commit is contained in:
James Nylen 2020-05-04 14:00:18 +00:00
parent eb88a9c631
commit 4460a4e34a
2 changed files with 29 additions and 2 deletions

View file

@ -566,6 +566,16 @@ exports.buildSearchData = data => {
// https://github.com/olivernn/lunr.js/issues/25#issuecomment-623267494
this.metadataWhitelist = ['position'];
// https://github.com/olivernn/lunr.js/issues/192#issuecomment-172915226
// https://gist.github.com/olivernn/7cd496f8654a0246c53c
function contractionTrimmer( token ) {
return token.update( str => {
return str.replace( /('m|'ve|n't|'d|'ll|'ve|'s|'re)$/, '' );
} );
}
lunr.Pipeline.registerFunction( contractionTrimmer, 'contractionTrimmer' );
this.pipeline.after( lunr.trimmer, contractionTrimmer );
Object.keys( textData ).forEach( c => this.add( textData[ c ] ) );
} );

View file

@ -30,9 +30,26 @@ function setupSearch() {
return;
}
var searchValue = searchInput.value.trim();
var searchValue = searchInput.value
.replace( /[^a-z0-9']+/gi, ' ' )
.trim()
.split( ' ' )
.filter( function( term ) {
return !! lunr.stopWordFilter( term );
} )
.map( function( term ) {
term = term
.replace( /('m|'ve|n't|'d|'ll|'ve|'s|'re)$/, '' )
.replace( /'/g, '' );
if ( term ) {
return '+' + term;
} else {
return term;
}
} )
.join( ' ' );
var allMatch = ! searchValue;
var searchResults = searchValue ? searchIndex.search( searchInput.value ) : [];
var searchResults = searchValue ? searchIndex.search( searchValue ) : [];
if ( allMatch ) {
searchStatus.innerHTML = ' ';
} else if ( searchResults.length === 1 ) {