engine.js 6.01 KB
Newer Older
1 2 3
const _ = require('lodash')
const { SearchService, QueryType } = require('azure-search-client')
const request = require('request-promise')
4 5 6
const stream = require('stream')
const Promise = require('bluebird')
const pipeline = Promise.promisify(stream.pipeline)
7

Nick's avatar
Nick committed
8 9
/* global WIKI */

10 11 12
module.exports = {
  async activate() {
    // not used
13
  },
14 15
  async deactivate() {
    // not used
16
  },
17 18 19 20
  /**
   * INIT
   */
  async init() {
21
    WIKI.logger.info(`(SEARCH/AZURE) Initializing...`)
22
    this.client = new SearchService(this.config.serviceName, this.config.adminKey)
23

24 25 26
    // -> Create Search Index
    const indexes = await this.client.indexes.list()
    if (!_.find(_.get(indexes, 'result.value', []), ['name', this.config.indexName])) {
Nick's avatar
Nick committed
27
      WIKI.logger.info(`(SEARCH/AZURE) Creating index...`)
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
      await this.client.indexes.create({
        name: this.config.indexName,
        fields: [
          {
            name: 'id',
            type: 'Edm.String',
            key: true,
            searchable: false
          },
          {
            name: 'locale',
            type: 'Edm.String',
            searchable: false
          },
          {
            name: 'path',
            type: 'Edm.String',
            searchable: false
          },
          {
            name: 'title',
            type: 'Edm.String',
            searchable: true
          },
          {
            name: 'description',
            type: 'Edm.String',
            searchable: true
          },
          {
            name: 'content',
            type: 'Edm.String',
            searchable: true
          }
        ],
        scoringProfiles: [
          {
            name: 'fieldWeights',
            text: {
              weights: {
                title: 4,
                description: 3,
                content: 1
              }
            }
          }
        ],
        suggesters: [
          {
            name: 'suggestions',
            searchMode: 'analyzingInfixMatching',
            sourceFields: ['title', 'description', 'content']
          }
Nick's avatar
Nick committed
81
        ]
82 83
      })
    }
84
    WIKI.logger.info(`(SEARCH/AZURE) Initialization completed.`)
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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  /**
   * QUERY
   *
   * @param {String} q Query
   * @param {Object} opts Additional options
   */
  async query(q, opts) {
    try {
      let suggestions = []
      const results = await this.client.indexes.use(this.config.indexName).search({
        count: true,
        scoringProfile: 'fieldWeights',
        search: q,
        select: 'id, locale, path, title, description',
        queryType: QueryType.simple,
        top: 50
      })
      if (results.result.value.length < 5) {
        // Using plain request, not yet available in library...
        try {
          const suggestResults = await request({
            uri: `https://${this.config.serviceName}.search.windows.net/indexes/${this.config.indexName}/docs/autocomplete`,
            method: 'post',
            qs: {
              'api-version': '2017-11-11-Preview'
            },
            headers: {
              'api-key': this.config.adminKey,
              'Content-Type': 'application/json'
            },
            json: true,
            body: {
              autocompleteMode: 'oneTermWithContext',
              search: q,
              suggesterName: 'suggestions'
            }
          })
          suggestions = suggestResults.value.map(s => s.queryPlusText)
        } catch (err) {
          WIKI.logger.warn('Search Engine suggestion failure: ', err)
        }
      }
      return {
        results: results.result.value,
        suggestions,
        totalHits: results.result['@odata.count']
      }
    } catch (err) {
      WIKI.logger.warn('Search Engine Error:')
      WIKI.logger.warn(err)
    }
137
  },
138 139 140 141 142 143 144 145 146 147 148 149 150
  /**
   * CREATE
   *
   * @param {Object} page Page to create
   */
  async created(page) {
    await this.client.indexes.use(this.config.indexName).index([
      {
        id: page.hash,
        locale: page.localeCode,
        path: page.path,
        title: page.title,
        description: page.description,
151
        content: page.safeContent
152 153
      }
    ])
154
  },
155 156 157 158 159 160 161 162 163 164 165 166 167
  /**
   * UPDATE
   *
   * @param {Object} page Page to update
   */
  async updated(page) {
    await this.client.indexes.use(this.config.indexName).index([
      {
        id: page.hash,
        locale: page.localeCode,
        path: page.path,
        title: page.title,
        description: page.description,
168
        content: page.safeContent
169 170
      }
    ])
171
  },
172 173 174 175 176 177 178 179 180 181 182 183
  /**
   * DELETE
   *
   * @param {Object} page Page to delete
   */
  async deleted(page) {
    await this.client.indexes.use(this.config.indexName).index([
      {
        '@search.action': 'delete',
        id: page.hash
      }
    ])
184
  },
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  /**
   * RENAME
   *
   * @param {Object} page Page to rename
   */
  async renamed(page) {
    await this.client.indexes.use(this.config.indexName).index([
      {
        '@search.action': 'delete',
        id: page.sourceHash
      }
    ])
    await this.client.indexes.use(this.config.indexName).index([
      {
        id: page.destinationHash,
        locale: page.localeCode,
        path: page.destinationPath,
        title: page.title,
        description: page.description,
204
        content: page.safeContent
205 206 207 208 209 210 211
      }
    ])
  },
  /**
   * REBUILD INDEX
   */
  async rebuild() {
212
    WIKI.logger.info(`(SEARCH/AZURE) Rebuilding Index...`)
213
    await pipeline(
214
      WIKI.models.knex.column({ id: 'hash' }, 'path', { locale: 'localeCode' }, 'title', 'description', 'render').select().from('pages').where({
215 216 217
        isPublished: true,
        isPrivate: false
      }).stream(),
218 219 220 221 222 223 224 225 226 227 228 229 230
      new stream.Transform({
        objectMode: true,
        transform: (chunk, enc, cb) => {
          cb(null, {
            id: chunk.id,
            path: chunk.path,
            locale: chunk.locale,
            title: chunk.title,
            description: chunk.description,
            content: WIKI.models.pages.cleanHTML(chunk.render)
          })
        }
      }),
231 232
      this.client.indexes.use(this.config.indexName).createIndexingStream()
    )
233
    WIKI.logger.info(`(SEARCH/AZURE) Index rebuilt successfully.`)
234 235
  }
}