All files / node-collections-boilerplate-nahid/search ElasticSearch.js

100% Statements 91/91
97.37% Branches 37/38
100% Functions 25/25
100% Lines 89/89
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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 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 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343                        1x 1x                                 16x             16x   16x                               16x 16x   16x         16x       65x         16x 16x 16x 39x 26x     16x 16x   26x       26x 26x 26x   16x 16x   39x     39x             39x   26x     16x                     16x   16x         16x                                         16x               16x 16x                     68x                 69x 69x 69x 69x   169x   13x     69x   69x                   1x                                 1x                         20x 20x   20x       20x   8x           12x   15x   2x 2x 2x       13x   3x 3x 3x       10x   4x 4x 4x   3x   4x   3x   4x       6x   5x 5x 5x   5x 10x   5x 5x           1x         20x   19x       1x             20x       20x 20x   16x       4x   20x 20x               48x 20x             1x  
/**
 * @file
 *
 * @author Nahid Akbar
 * @year 2016
 * @copyright Data61 -
 *            Commonwealth Scientific and Industrial Research Organisation (CSIRO) -
 *            Australian Government. All rights reserved.
 */
 
"use strict";
 
const Search = require('./Search');
const elasticsearch = require('elasticsearch');
 
/**
 * Search using ElasticSearch.
 * Needs to be revised at 10000 records.
 * Needs ```elasticsearch``` package.
 */
class ElasticSearch extends Search
{
  /**
   * @override
   */
  async connect()
  {
    /**
     * reference to driver object
     */
    this.client = new elasticsearch.Client({
      host: this.connectionString,
      maxRetries: 90 * 1024,
      maxSockets: 1,
      requestTimeout: 1024 * 1024,
      sniffOnConnectionFault: true
    });
    try
    {
      await this.client.indices.delete({
        index: this.collectionName,
      });
    }
    catch (e)
    {
      // might fail if this is the first time
    }
  }
 
  /**
   * @override
   */
  initialise(searchMeta, records)
  {
    /** store for later use */
    this.searchMeta = searchMeta;
    return new Promise((resolve, reject) =>
    {
      this.client.indices.create({
          index: this.collectionName,
        })
        .then(() =>
        {
          let that = this;
 
          function upload()
          {
            resolve(Promise.all(records.map(record => that.createRecord(record))));
          }
 
          function sort()
          {
            let properties = {};
            let fields = searchMeta.fields || {};
            Object.keys(fields)
              .filter(f => !fields[f].dummy)
              .forEach(field => properties[field] = {
                type: "keyword"
              });
            let weights = Object.keys(searchMeta.searchWeights || {});
            weights.forEach(field =>
            {
              properties[field] = properties[field] || {
                type: "text",
                fielddata: true
              };
              properties[field].type = "text";
              properties[field].fielddata = true;
              properties[field].analyzer = "fulltext_analyzer";
            });
            let sorts = searchMeta.sort || [];
            sorts.forEach(field =>
            {
              properties[field] = properties[field] || {
                type: "text",
              };
              properties[field].fields = {
                case_insensitive: {
                  "type": "string",
                  "analyzer": "case_insensitive",
                  fielddata: true
                }
              }
              if (properties[field].type === 'text')
              {
                properties[field].fielddata = true;
              }
            });
            return that.client.indices.putMapping({
              index: that.collectionName,
              type: that.collectionName,
              body: {
                properties
              },
            });
          }
 
          function analyse()
          {
            return new Promise((resolve, reject) =>
            {
              that.client.indices.close({
                  index: that.collectionName
                })
                .then(() =>
                {
                  that.client.indices.putSettings({
                      index: that.collectionName,
                      body: {
                        "settings": {
                          "analysis": {
                            "analyzer": {
                              "fulltext_analyzer": {
                                "tokenizer": "standard",
                                "filter": ["standard", "lowercase", "asciifolding", "porter_stem"]
                              },
                              "case_insensitive": {
                                "tokenizer": "keyword",
                                "filter": ["lowercase", "asciifolding"]
                              }
                            }
                          }
                        }
                      }
                    })
                    .then(() =>
                    {
                      that.client.indices.open({
                          index: that.collectionName
                        })
                        .then(resolve, reject);
                    }, reject);
                }, reject);
            });
          }
          analyse()
            .then(() => sort()
              .then(upload, reject), reject);
        }, reject);
    });
  }
 
  /**
   * @override
   */
  createRecord(record)
  {
    return this.updateRecord(record);
  }
 
  /**
   * @override
   * TODO: I think there is a bug with exisint record
   */
  async updateRecord(record)
  {
    record = Object.assign({}, record);
    const id = record[this.primaryKey];
    delete record[this.primaryKey];
    for (let x in record)
    {
      if (x.match(/(^_|password|roles|meta)/g))
      {
        delete record[x];
      }
    }
    try
    {
      return await this.client.create({
        index: this.collectionName,
        type: this.collectionName,
        id: id,
        body: record,
        refresh: true
      });
    }
    catch (e)
    {
      return await this.client.update({
        index: this.collectionName,
        type: this.collectionName,
        id: id,
        body: {
          doc: record
        },
        refresh: true
      });
    }
  }
 
  /**
   * @override
   */
  deleteRecord(record)
  {
    return this.client.delete({
      index: this.collectionName,
      type: this.collectionName,
      id: record[this.primaryKey],
      refresh: true
    });
  }
 
  /**
   * @override
   */
  searchRecords(inquery)
  {
    const searchMeta = this.searchMeta;
    return new Promise((resolve, reject) =>
    {
      let query = [
 
      ];
 
      if (inquery.filter.length === 0)
      {
        query.push({
          match_all: {}
        });
      }
      else
      {
        inquery.filter.forEach(infilter =>
        {
          if (infilter.filter === 'equals')
          {
            let term = {};
            term[infilter.field] = infilter.value[0];
            query.push({
              term
            })
          }
          else if (infilter.filter === 'within')
          {
            let terms = {};
            terms[infilter.field] = infilter.value;
            query.push({
              terms
            })
          }
          else if (infilter.filter === 'regex')
          {
            let regexp = {};
            regexp[infilter.field] = infilter.value[0];
            if (regexp[infilter.field].match(/^\^/))
            {
              regexp[infilter.field] = regexp[infilter.field].substr(1)
            }
            if (regexp[infilter.field].match(/\$$/))
            {
              regexp[infilter.field] = regexp[infilter.field].substr(0, regexp[infilter.field].length - 1)
            }
            query.push({
              regexp
            })
          }
          else if (infilter.filter === 'search')
          {
            let query_string = {};
            query_string.query = infilter.value[0];
            Eif (searchMeta.searchWeights)
            {
              query_string.fields = Object.keys(searchMeta.searchWeights)
                .map(key => `${key}^${searchMeta.searchWeights[key]}`);
            }
            query_string.analyzer = "fulltext_analyzer";
            query.push({
              query_string
            })
          }
          else
          {
            console.error('Unhandelled Filter', infilter);
          }
        });
      }
 
      if (query.length === 1)
      {
        query = query[0];
      }
      else
      {
        query = {
          bool: {
            must: query
          }
        };
      }
 
      let body = {
        query
      };
 
      body.sort = {};
      if (!inquery.sort || inquery.sort === "search")
      {
        inquery.sort = '_score';
      }
      else
      {
        inquery.sort += '.case_insensitive'
      }
      body.sort[inquery.sort] = inquery.order === 'dsc' ? 'desc' : 'asc';
      this.client.search({
          index: this.collectionName,
          body,
          size: 10000,
          _source: false
        })
        .then(results =>
        {
          results = results.hits.hits.map(h => h._id);
          resolve(results);
        }, reject);
    });
  }
 
}
 
module.exports = ElasticSearch;