search.js 3.39 KB
Newer Older
1 2 3 4 5
"use strict";

var Promise = require('bluebird'),
	_ = require('lodash'),
	path = require('path'),
6
	searchIndex = require('search-index'),
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
	stopWord = require('stopword');

/**
 * Search Model
 */
module.exports = {

	_si: null,

	/**
	 * Initialize Search model
	 *
	 * @param      {Object}  appconfig  The application config
	 * @return     {Object}  Search model instance
	 */
	init(appconfig) {

24
		let self = this;
25 26
		let dbPath = path.resolve(ROOTPATH, appconfig.datadir.db, 'search-index');

27
		searchIndex({
28 29 30 31 32 33 34 35
			deletable: true,
			fieldedSearch: true,
			indexPath: dbPath,
			logLevel: 'error',
			stopwords: stopWord.getStopwords(appconfig.lang).sort()
		}, (err, si) => {
			if(err) {
				winston.error('Failed to initialize search-index.', err);
36 37
			} else {
				self._si = Promise.promisifyAll(si);
38 39 40
			}
		});

41 42 43 44 45 46 47 48 49 50 51 52 53
		return self;

	},

	find(terms) {

		let self = this;
		terms = _.chain(terms)
							.deburr()
							.toLower()
							.trim()
							.replace(/[^a-z0-9 ]/g, '')
							.value();
54

NGPixel's avatar
NGPixel committed
55 56 57 58 59 60
		let arrTerms = _.chain(terms)
										.split(' ')
										.filter((f) => { return !_.isEmpty(f); })
										.value();


61 62
		return self._si.searchAsync({
			query: {
NGPixel's avatar
NGPixel committed
63
				AND: [{ '*': arrTerms }]
64 65
			},
			pageSize: 10
NGPixel's avatar
NGPixel committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
		}).get('hits').then((hits) => {

			if(hits.length < 5) {
				return self._si.matchAsync({
					beginsWith: terms,
					threshold: 3,
					limit: 5,
					type: 'simple'
				}).then((matches) => {

					return {
						match: hits,
						suggest: matches
					};

				});
			} else {
				return {
					match: hits,
					suggest: []
				};
			}

89 90 91 92 93 94 95 96 97 98 99
		}).catch((err) => {

			if(err.type === 'NotFoundError') {
				return {
					match: [],
					suggest: []
				};
			} else {
				winston.error(err);
			}

NGPixel's avatar
NGPixel committed
100
		});
101

102 103 104 105 106 107 108 109 110 111 112 113
	},

	/**
	 * Add a document to the index
	 *
	 * @param      {Object}   content  Document content
	 * @return     {Promise}  Promise of the add operation
	 */
	add(content) {

		let self = this;

NGPixel's avatar
NGPixel committed
114
		return self.delete(content.entryPath).then(() => {
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

			return self._si.addAsync({
				entryPath: content.entryPath,
				title: content.meta.title,
				subtitle: content.meta.subtitle || '',
				parent: content.parent.title || '',
				content: content.text || ''
			}, {
				fieldOptions: [{
					fieldName: 'entryPath',
					searchable: true,
					weight: 2
				},
				{
					fieldName: 'title',
					nGramLength: [1, 2],
					searchable: true,
					weight: 3
				},
				{
					fieldName: 'subtitle',
					searchable: true,
					weight: 1,
					store: false
				},
				{
					fieldName: 'parent',
					searchable: false,
				},
				{
					fieldName: 'content',
					searchable: true,
					weight: 0,
					store: false
				}]
			}).then(() => {
				winston.info('Entry ' + content.entryPath + ' added/updated to index.');
				return true;
			}).catch((err) => {
				winston.error(err);
			});

157 158 159 160
		}).catch((err) => {
			winston.error(err);
		});

NGPixel's avatar
NGPixel committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
	},

	/**
	 * Delete an entry from the index
	 *
	 * @param      {String}   The     entry path
	 * @return     {Promise}  Promise of the operation
	 */
	delete(entryPath) {

		let self = this;

		return self._si.searchAsync({
			query: {
				AND: [{ 'entryPath': [entryPath] }]
			}
		}).then((results) => {

			if(results.totalHits > 0) {
				let delIds = _.map(results.hits, 'id');
				return self._si.delAsync(delIds);
			} else {
				return true;
			}

		}).catch((err) => {

			if(err.type === 'NotFoundError') {
				return true;
			} else {
				winston.error(err);
			}

		});

196
	}
197 198

};