All files / src System.js

97.22% Statements 105/108
87.72% Branches 50/57
95.65% Functions 22/23
97.17% Lines 103/106
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 344 345 346 347 348 349 350    9x 9x 9x 9x                                                 131x     116x           131x             131x           131x   268x         131x         131x     29x 29x   29x     29x   66x     29x     131x         131x     7x 7x   9x 9x   7x                   29x     29x 7x                   102x 102x   94x     102x   230x     102x         18x 18x   24x 24x   18x                         104x 104x   104x   104x   5x                   21x 21x   21x   21x       21x                                           99x   93x       93x   93x   14x   93x   6x               119x     8x   5x   3x   103x           106x 106x   106x 106x 106x   106x               8x 8x   16x 16x   8x       8x     8x               5x 5x   10x 10x   5x               3x 3x               970x 970x 970x   771x 771x   771x   771x 771x   970x           21x   199x 199x 199x                 91x 91x 91x   91x     91x   91x 91x       91x         9x  
"use strict";
 
const indicesRegister = require('./index/register');
const processorRegister = require('./processors/register');
const Results = require('./Results');
const scores = require('./scores');
/**
 * Information Retrieval System Main Class
 *
 * Basic workflow is:
 *
 * * create a new IRSystem
 * * add indices
 * * manage(add/remove/update)/retrive document collection/sets
 *
 * or:
 *
 * * create a new IRSystem with saved state from another IRSystem
 * * manage(add/remove/update)/retrive documents
 *
 */
class System
{
  /**
   * Construct new IR system.
   *
   * @param {IRSystem} [config={}] configuration/state. Can be result of state(). See attributes.
   */
  constructor(config = {})
  {
    for (let property in config)
    {
      /** @private */
      this[property] = config[property];
    }
    /**
     * id field name
     * @type {string}
     */
    this.idField = this.idField || 'id';
 
    /**
     * list of ids
     * index -> id
     * @private
     */
    this.ids = this.ids || [];
    /**
     * id lookup
     * id => index
     * @private
     */
    this.idLookup = this.idLookup || {};
    // rebuild ids table
    this.ids.forEach((id, index) => this.idLookup[id] = index);
    /**
     * name => index
     * @private
     */
    this.indicesLookup = {};
    /**
     * system indices
     * @type {Index[]}
     */
    this.indices = (this.indices || [])
      .map(object =>
      {
        object = new(indicesRegister.lookup[object.type])(object);
        Eif (object.name)
        {
          (this.indicesLookup[object.name] || (this.indicesLookup[object.name] = []))
          .push(object);
        }
        for (let filter of object.filters)
        {
          (this.indicesLookup[filter] || (this.indicesLookup[filter] = []))
          .push(object);
        }
        return object;
      });
 
    this.processorsLookup = {};
    /**
     * system processors
     * @type {Processor[]}
     */
    this.processors = (this.processors || [])
      .map(object =>
      {
        object = new(processorRegister.lookup[object.type])(object);
        for (let bind of object.bind)
        {
          this.processorsLookup[bind] = this.processorsLookup[bind] || [];
          this.processorsLookup[bind].push(object);
        }
        return object;
      });
  }
 
  /**
   * Dump current system state
   * @return {object}
   */
  async state()
  {
    return {
      idField: this.idField,
      ids: this.ids,
      indices: await Promise.all(this.indices.map(index => index.state())),
      processors: await Promise.all(this.processors.map(processor => processor.state())),
    };
  }
 
  /**
   * Add a new index to the system.
   * @return {IRSystem}
   */
  addIndex(index)
  {
    this.indices.push(index);
    if (index.name)
    {
      (this.indicesLookup[index.name] || (this.indicesLookup[index.name] = []))
      .push(index);
    }
    for (let filter of index.filters)
    {
      (this.indicesLookup[filter] || (this.indicesLookup[filter] = []))
      .push(index);
    }
    return this;
  }
 
  addProcessor(processor)
  {
    this.processors.push(processor);
    for (let bind of processor.bind)
    {
      this.processorsLookup[bind] = this.processorsLookup[bind] || [];
      this.processorsLookup[bind].push(processor);
    }
    return this;
  }
 
  /**
   * Add a set of documents to the IR system.
   *
   * Documents are added and removed in bulk for abusing any potential
   * optimisations which might be available for doing things in bulk.
   *
   * @param {Document[]} documents document set to add
   */
  async addDocuments(documents = [])
  {
    const documentIndices = documents.map(this.helperGetIndex.bind(this));
    for (let index of this.indices)
    {
      await index.addDocuments(documentIndices, documents);
    }
    for (let processor of (this.processorsLookup['add'] || []))
    {
      await processor.addDocuments(this, documentIndices, documents);
    }
  }
 
  /**
   * Remove a set of documents from the IR system.
   * @param {Document[]} documents document set to add
   */
  async removeDocuments(documents = [])
  {
    const documentIndices = documents.map(this.helperGetIndex.bind(this));
    for (let index of this.indices)
    {
      await index.removeDocuments(documentIndices);
    }
    for (let processor of (this.processorsLookup['remove'] || []))
    {
      await processor.removeDocuments(this, documentIndices);
    }
    this.helperRemoveIndices(documentIndices);
  }
 
  /**
   * Alias of addDocuments.
   *
   * Add is the same as update in this system.
   *
   * @param {Document[]} documents document set to add
   */
  updateDocuments(documents = [])
  {
    return this.addDocuments(documents);
  }
 
  /**
   * Retrieve a list of documents that matches a query.
   * @param {Query} query query
   * @return {Document[]} retrieve
   */
  async retrieveDocuments(query, score = scores.naiveBayes)
  {
    if (query && query.filter)
    {
      for (let processor of (this.processorsLookup['query'] || []))
      {
        await processor.processQuery(this, query);
      }
      const results = (await this.getResults(query.filter, score))
        .normalise(this);
      for (let processor of (this.processorsLookup['results'] || []))
      {
        await processor.processResults(this, query, results);
      }
      return results;
    }
    return {};
  }
 
  /**
   * @protected
   */
  async getResults(filter, score)
  {
    switch (filter.filter)
    {
    case 'and':
      return await this.getAndResults(filter.values, score);
    case 'or':
      return await this.getOrResults(filter.values, score);
    case 'not':
      return await this.getNotResults(filter.values, score);
    default:
      return await this.getFilterResults(filter, score);
    }
  }
 
  async getFilterResults(filter, score)
  {
    let results = new Results();
    for (let index of (this.indicesLookup[filter.field || filter.filter] || []))
    {
      const newResults = new Results();
      await index.filterDocuments(filter, newResults, score);
      results = results.concat(newResults);
    }
    return results;
  }
 
  /**
   * @protected
   */
  async getAndResults(values, score)
  {
    let results = undefined;
    for (let filter of values)
    {
      let filterResults = await this.getResults(filter, score);
      if (!results)
      {
        results = filterResults;
      }
      else
      {
        results = results.merge(filterResults);
      }
    }
    return results;
  }
 
  /**
   * @protected
   */
  async getOrResults(values, score)
  {
    let results = new Results();
    for (let filter of values)
    {
      let filterResults = await this.getResults(filter, score);
      results = results.concat(filterResults);
    }
    return results;
  }
 
  /**
   * @protected
   */
  async getNotResults(filter, score)
  {
    const results = await this.getFilterResults(filter, score);
    return results.invert(this.ids);
  }
 
  /**
   * @protected
   */
  helperGetIndex(record)
  {
    const id = record[this.idField];
    let lookup = this.idLookup[id];
    if (lookup === undefined)
    {
      lookup = this.ids.indexOf(null);
      Eif (lookup === -1)
      {
        lookup = this.ids.length;
      }
      this.idLookup[id] = lookup
      this.ids[lookup] = id
    }
    return lookup;
  }
 
 
  helperRemoveIndices(indices)
  {
    indices.forEach(index =>
    {
      const id = this.ids[index];
      delete this.idLookup[id];
      this.ids[index] = null;
    })
  }
 
  /**
   * @public
   */
  meta()
  {
    const fields = {};
    let sort = {};
    for (let index of this.indices)
    {
      fields[index.name] = {
        filters: index.filters
      }
      index.sorts.forEach(key => sort[key] = 1);
    }
    sort = Object.keys(sort);
    const meta = {
      fields,
      sort
    };
    return meta;
  }
 
}
 
module.exports = System;