search.js 4.7 KB
Newer Older
1 2 3 4
'use strict'

const Promise = require('bluebird')
const _ = require('lodash')
5
const searchIndex = require('./search-index')
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
const stopWord = require('stopword')
const streamToPromise = require('stream-to-promise')

module.exports = {

  _si: null,
  _isReady: false,

  /**
   * Initialize search index
   *
   * @return {undefined} Void
   */
  init () {
    let self = this
    self._isReady = new Promise((resolve, reject) => {
      searchIndex({
        deletable: true,
        fieldedSearch: true,
25
        indexPath: 'wiki',
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        logLevel: 'error',
        stopwords: _.get(stopWord, appconfig.lang, [])
      }, (err, si) => {
        if (err) {
          winston.error('[SERVER.Search] Failed to initialize search index.', err)
          reject(err)
        } else {
          self._si = Promise.promisifyAll(si)
          self._si.flushAsync().then(() => {
            winston.info('[SERVER.Search] Search index flushed and ready.')
            resolve(true)
          })
        }
      })
    })

    return self
  },

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

    return self._isReady.then(() => {
      return self.delete(content._id).then(() => {
        return self._si.concurrentAddAsync({
          fieldOptions: [{
            fieldName: 'entryPath',
            searchable: true,
            weight: 2
          },
          {
            fieldName: 'title',
            nGramLength: [1, 2],
            searchable: true,
            weight: 3
          },
          {
            fieldName: 'subtitle',
            searchable: true,
            weight: 1,
            storeable: false
          },
          {
            fieldName: 'parent',
            searchable: false
          },
          {
            fieldName: 'content',
            searchable: true,
            weight: 0,
            storeable: false
          }]
        }, [{
          entryPath: content._id,
          title: content.title,
          subtitle: content.subtitle || '',
          parent: content.parent || '',
          content: content.content || ''
        }]).then(() => {
          winston.log('verbose', '[SERVER.Search] Entry ' + content._id + ' added/updated to index.')
          return true
        }).catch((err) => {
          winston.error(err)
        })
      }).catch((err) => {
        winston.error(err)
      })
    })
  },

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

    return self._isReady.then(() => {
      return streamToPromise(self._si.search({
        query: [{
          AND: { 'entryPath': [entryPath] }
        }]
      })).then((results) => {
117 118
        if (results && results.length > 0) {
          let delIds = _.map(results, 'id')
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 157 158 159 160 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 196 197 198 199 200 201 202 203 204
          return self._si.delAsync(delIds)
        } else {
          return true
        }
      }).catch((err) => {
        if (err.type === 'NotFoundError') {
          return true
        } else {
          winston.error(err)
        }
      })
    })
  },

  /**
   * Flush the index
   *
   * @returns {Promise} Promise of the flush operation
   */
  flush () {
    let self = this
    return self._isReady.then(() => {
      return self._si.flushAsync()
    })
  },

  /**
   * Search the index
   *
   * @param {Array<String>} terms
   * @returns {Promise<Object>} Hits and suggestions
   */
  find (terms) {
    let self = this
    terms = _.chain(terms)
              .deburr()
              .toLower()
              .trim()
              .replace(/[^a-z0-9 ]/g, '')
              .value()
    let arrTerms = _.chain(terms)
                    .split(' ')
                    .filter((f) => { return !_.isEmpty(f) })
                    .value()

    return streamToPromise(self._si.search({
      query: [{
        AND: { '*': arrTerms }
      }],
      pageSize: 10
    })).then((hits) => {
      if (hits.length > 0) {
        hits = _.map(_.sortBy(hits, ['score']), h => {
          return h.document
        })
      }
      if (hits.length < 5) {
        return streamToPromise(self._si.match({
          beginsWith: terms,
          threshold: 3,
          limit: 5,
          type: 'simple'
        })).then((matches) => {
          return {
            match: hits,
            suggest: matches
          }
        })
      } else {
        return {
          match: hits,
          suggest: []
        }
      }
    }).catch((err) => {
      if (err.type === 'NotFoundError') {
        return {
          match: [],
          suggest: []
        }
      } else {
        winston.error(err)
      }
    })
  }
}