itemsjs
Version:
Created to perform fast search on small json dataset (up to 1000 elements).
91 lines (72 loc) • 1.93 kB
JavaScript
var _ = require('./../vendor/lodash');
var lunr = require('lunr');
/**
* responsible for making full text searching on items
* config provide only searchableFields
*/
var Fulltext = function Fulltext(items, config) {
var _this = this;
config = config || {};
config.searchableFields = config.searchableFields || [];
this.items = items; // creating index
this.idx = lunr(function () {
// currently schema hardcoded
this.field('name', {
boost: 10
});
var self = this;
_.forEach(config.searchableFields, function (field) {
self.field(field);
});
this.ref('_id');
/**
* Remove the stemmer and stopWordFilter from the pipeline
* stemmer: https://github.com/olivernn/lunr.js/issues/328
* stopWordFilter: https://github.com/olivernn/lunr.js/issues/233
*/
if (config.isExactSearch) {
this.pipeline.remove(lunr.stemmer);
this.pipeline.remove(lunr.stopWordFilter);
}
});
var i = 1;
_.map(items, function (item) {
item._id = i;
++i;
_this.idx.add(item);
});
this.store = _.mapKeys(items, function (doc) {
return doc._id;
});
};
Fulltext.prototype = {
search_full: function search_full(query, filter) {
var _this2 = this;
return this.search(query, filter).map(function (v) {
return _this2.store[v];
});
},
search: function search(query, filter) {
var _this3 = this;
if (!query && !filter) {
return this.items ? this.items.map(function (v) {
return v._id;
}) : [];
}
var items;
if (query) {
items = _.map(this.idx.search(query), function (val) {
var item = _this3.store[val.ref];
return item;
});
}
if (filter instanceof Function) {
items = (items || this.items).filter(filter);
}
return items.map(function (v) {
return v._id;
});
}
};
module.exports = Fulltext;
;