engine.js 8.67 KB
Newer Older
Nick's avatar
Nick committed
1
const _ = require('lodash')
2 3 4
const stream = require('stream')
const Promise = require('bluebird')
const pipeline = Promise.promisify(stream.pipeline)
5

Nick's avatar
Nick committed
6
/* global WIKI */
7

Nick's avatar
Nick committed
8 9 10
module.exports = {
  async activate() {
    // not used
11
  },
Nick's avatar
Nick committed
12 13
  async deactivate() {
    // not used
14
  },
Nick's avatar
Nick committed
15 16 17 18 19
  /**
   * INIT
   */
  async init() {
    WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Initializing...`)
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    switch (this.config.apiVersion) {
      case '7.x':
        const { Client: Client7 } = require('elasticsearch7')
        this.client = new Client7({
          nodes: this.config.hosts.split(',').map(_.trim),
          sniffOnStart: this.config.sniffOnStart,
          sniffInterval: (this.config.sniffInterval > 0) ? this.config.sniffInterval : false,
          name: 'wiki-js'
        })
        break
      case '6.x':
        const { Client: Client6 } = require('elasticsearch6')
        this.client = new Client6({
          nodes: this.config.hosts.split(',').map(_.trim),
          sniffOnStart: this.config.sniffOnStart,
          sniffInterval: (this.config.sniffInterval > 0) ? this.config.sniffInterval : false,
          name: 'wiki-js'
        })
        break
      default:
        throw new Error('Unsupported version of elasticsearch! Update your settings in the Administration Area.')
    }
42

Nick's avatar
Nick committed
43 44
    // -> Create Search Index
    await this.createIndex()
45

Nick's avatar
Nick committed
46
    WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Initialization completed.`)
47
  },
Nick's avatar
Nick committed
48 49 50 51
  /**
   * Create Index
   */
  async createIndex() {
52 53 54 55 56 57 58 59 60 61 62 63 64
    try {
      const indexExists = await this.client.indices.exists({ index: this.config.indexName })
      if (!indexExists.body) {
        WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Creating index...`)
        try {
          const idxBody = {
            properties: {
              suggest: { type: 'completion' },
              title: { type: 'text', boost: 4.0 },
              description: { type: 'text', boost: 3.0 },
              content: { type: 'text', boost: 1.0 },
              locale: { type: 'keyword' },
              path: { type: 'text' }
Nick's avatar
Nick committed
65 66
            }
          }
67 68 69 70 71 72 73 74 75 76
          await this.client.indices.create({
            index: this.config.indexName,
            body: {
              mappings: (this.config.apiVersion === '6.x') ? {
                _doc: idxBody
              } : idxBody
            }
          })
        } catch (err) {
          WIKI.logger.error(`(SEARCH/ELASTICSEARCH) Create Index Error: `, _.get(err, 'meta.body.error', err))
Nick's avatar
Nick committed
77
        }
78 79 80
      }
    } catch (err) {
      WIKI.logger.error(`(SEARCH/ELASTICSEARCH) Index Check Error: `, _.get(err, 'meta.body.error', err))
Nick's avatar
Nick committed
81
    }
82
  },
Nick's avatar
Nick committed
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
  /**
   * QUERY
   *
   * @param {String} q Query
   * @param {Object} opts Additional options
   */
  async query(q, opts) {
    try {
      const results = await this.client.search({
        index: this.config.indexName,
        body: {
          query: {
            simple_query_string: {
              query: q
            }
          },
          from: 0,
          size: 50,
          _source: ['title', 'description', 'path', 'locale'],
          suggest: {
            suggestions: {
              text: q,
              completion: {
                field: 'suggest',
                size: 5,
                skip_duplicates: true,
                fuzzy: true
              }
            }
          }
        }
      })
      return {
116
        results: _.get(results, 'body.hits.hits', []).map(r => ({
Nick's avatar
Nick committed
117 118 119 120 121 122 123
          id: r._id,
          locale: r._source.locale,
          path: r._source.path,
          title: r._source.title,
          description: r._source.description
        })),
        suggestions: _.reject(_.get(results, 'suggest.suggestions', []).map(s => _.get(s, 'options[0].text', false)), s => !s),
124
        totalHits: _.get(results, 'body.hits.total.value', _.get(results, 'body.hits.total', 0))
Nick's avatar
Nick committed
125 126
      }
    } catch (err) {
127
      WIKI.logger.warn('Search Engine Error: ', _.get(err, 'meta.body.error', err))
Nick's avatar
Nick committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    }
  },
  /**
   * Build suggest field
   */
  buildSuggest(page) {
    return _.uniq(_.concat(
      page.title.split(' ').map(s => ({
        input: s,
        weight: 4
      })),
      page.description.split(' ').map(s => ({
        input: s,
        weight: 3
      })),
143
      page.safeContent.split(' ').map(s => ({
Nick's avatar
Nick committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        input: s,
        weight: 1
      }))
    ))
  },
  /**
   * CREATE
   *
   * @param {Object} page Page to create
   */
  async created(page) {
    await this.client.index({
      index: this.config.indexName,
      type: '_doc',
      id: page.hash,
      body: {
        suggest: this.buildSuggest(page),
        locale: page.localeCode,
        path: page.path,
        title: page.title,
        description: page.description,
165
        content: page.safeContent
Nick's avatar
Nick committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
      },
      refresh: true
    })
  },
  /**
   * UPDATE
   *
   * @param {Object} page Page to update
   */
  async updated(page) {
    await this.client.index({
      index: this.config.indexName,
      type: '_doc',
      id: page.hash,
      body: {
        suggest: this.buildSuggest(page),
        locale: page.localeCode,
        path: page.path,
        title: page.title,
        description: page.description,
186
        content: page.safeContent
Nick's avatar
Nick committed
187 188 189
      },
      refresh: true
    })
190
  },
Nick's avatar
Nick committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  /**
   * DELETE
   *
   * @param {Object} page Page to delete
   */
  async deleted(page) {
    await this.client.delete({
      index: this.config.indexName,
      type: '_doc',
      id: page.hash,
      refresh: true
    })
  },
  /**
   * RENAME
   *
   * @param {Object} page Page to rename
   */
  async renamed(page) {
    await this.client.delete({
      index: this.config.indexName,
      type: '_doc',
NGPixel's avatar
NGPixel committed
213
      id: page.hash,
Nick's avatar
Nick committed
214 215 216 217 218 219 220 221
      refresh: true
    })
    await this.client.index({
      index: this.config.indexName,
      type: '_doc',
      id: page.destinationHash,
      body: {
        suggest: this.buildSuggest(page),
NGPixel's avatar
NGPixel committed
222
        locale: page.destinationLocaleCode,
Nick's avatar
Nick committed
223 224 225
        path: page.destinationPath,
        title: page.title,
        description: page.description,
226
        content: page.safeContent
Nick's avatar
Nick committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      },
      refresh: true
    })
  },
  /**
   * REBUILD INDEX
   */
  async rebuild() {
    WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Rebuilding Index...`)
    await this.client.indices.delete({ index: this.config.indexName })
    await this.createIndex()

    const MAX_INDEXING_BYTES = 10 * Math.pow(2, 20) - Buffer.from('[').byteLength - Buffer.from(']').byteLength // 10 MB
    const MAX_INDEXING_COUNT = 1000
    const COMMA_BYTES = Buffer.from(',').byteLength

    let chunks = []
    let bytes = 0

    const processDocument = async (cb, doc) => {
      try {
        if (doc) {
          const docBytes = Buffer.from(JSON.stringify(doc)).byteLength

          // -> Current batch exceeds size limit, flush
          if (docBytes + COMMA_BYTES + bytes >= MAX_INDEXING_BYTES) {
            await flushBuffer()
          }

          if (chunks.length > 0) {
            bytes += COMMA_BYTES
          }
          bytes += docBytes
          chunks.push(doc)

          // -> Current batch exceeds count limit, flush
          if (chunks.length >= MAX_INDEXING_COUNT) {
            await flushBuffer()
          }
        } else {
          // -> End of stream, flush
          await flushBuffer()
        }
        cb()
      } catch (err) {
        cb(err)
      }
    }

    const flushBuffer = async () => {
      WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Sending batch of ${chunks.length}...`)
      try {
        await this.client.bulk({
          index: this.config.indexName,
          body: _.reduce(chunks, (result, doc) => {
            result.push({
              index: {
                _index: this.config.indexName,
                _type: '_doc',
                _id: doc.id
              }
            })
289
            doc.safeContent = WIKI.models.pages.cleanHTML(doc.render)
Nick's avatar
Nick committed
290 291 292 293 294 295
            result.push({
              suggest: this.buildSuggest(doc),
              locale: doc.locale,
              path: doc.path,
              title: doc.title,
              description: doc.description,
296
              content: doc.safeContent
Nick's avatar
Nick committed
297 298 299 300 301 302 303 304 305 306 307
            })
            return result
          }, []),
          refresh: true
        })
      } catch (err) {
        WIKI.logger.warn('(SEARCH/ELASTICSEARCH) Failed to send batch to elasticsearch: ', err)
      }
      chunks.length = 0
      bytes = 0
    }
308

Nick's avatar
Nick committed
309
    await pipeline(
310
      WIKI.models.knex.column({ id: 'hash' }, 'path', { locale: 'localeCode' }, 'title', 'description', 'render').select().from('pages').where({
Nick's avatar
Nick committed
311 312 313
        isPublished: true,
        isPrivate: false
      }).stream(),
314
      new stream.Transform({
Nick's avatar
Nick committed
315 316 317 318 319 320
        objectMode: true,
        transform: async (chunk, enc, cb) => processDocument(cb, chunk),
        flush: async (cb) => processDocument(cb)
      })
    )
    WIKI.logger.info(`(SEARCH/ELASTICSEARCH) Index rebuilt successfully.`)
321 322
  }
}