|
| 1 | +var lunr = require("lunr"); |
| 2 | +var searchEngine; |
| 3 | + |
| 4 | +module.exports = { |
| 5 | + indexData: function(items) { |
| 6 | + searchEngine = lunr(function() { |
| 7 | + lunr.tokenizer.separator = /[\s]+/; |
| 8 | + |
| 9 | + this.pipeline.remove(lunr.stemmer); |
| 10 | + this.pipeline.remove(lunr.stopWordFilter); |
| 11 | + this.pipeline.remove(lunr.trimmer); |
| 12 | + this.searchPipeline.remove(lunr.stemmer); |
| 13 | + |
| 14 | + this.ref('name'); |
| 15 | + this.field('title'); |
| 16 | + this.field('description'); |
| 17 | + this.field('name'); |
| 18 | + this.field('url'); |
| 19 | + |
| 20 | + items.forEach(function(item) { |
| 21 | + if (!item.title) { |
| 22 | + item.title = item.name; |
| 23 | + } |
| 24 | + this.add(item); |
| 25 | + }.bind(this)); |
| 26 | + }); |
| 27 | + return searchEngine; |
| 28 | + }, |
| 29 | + |
| 30 | + loadIndex: function(index) { |
| 31 | + return lunr.Index.load(index); |
| 32 | + }, |
| 33 | + |
| 34 | + search: function(value) { |
| 35 | + var searchTerm = value.toLowerCase(); |
| 36 | + |
| 37 | + //run the search |
| 38 | + return searchEngine.query(function(q) { |
| 39 | + |
| 40 | + if (searchTerm.indexOf('can-') > -1) {// If the search term includes “can-” |
| 41 | + |
| 42 | + // look for an exact match and apply a large positive boost |
| 43 | + q.term(searchTerm, { boost: 375 }); |
| 44 | + |
| 45 | + } else { |
| 46 | + // add “can-”, look for an exact match in the title field, and apply a positive boost |
| 47 | + q.term('can-' + searchTerm, { boost: 12 }); |
| 48 | + |
| 49 | + // look for terms that match the beginning or end of this query |
| 50 | + // look in the title field specifically to boost matches in it |
| 51 | + q.term(searchTerm, { fields: ['title'], wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING }); |
| 52 | + q.term(searchTerm, { wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING }); |
| 53 | + } |
| 54 | + |
| 55 | + // look for matches in any of the fields and apply a medium positive boost |
| 56 | + var split = searchTerm.split(lunr.tokenizer.separator); |
| 57 | + split.forEach(function(term) { |
| 58 | + q.term(term, { boost: 10, fields: q.allFields }); |
| 59 | + q.term(term, { fields: q.allFields, wildcard: lunr.Query.wildcard.TRAILING }); |
| 60 | + }); |
| 61 | + }); |
| 62 | + } |
| 63 | +}; |
0 commit comments