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

100% Statements 88/88
97.37% Branches 37/38
100% Functions 9/9
100% Lines 87/87
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                        1x 1x                         17x 17x 17x       17x 17x 17x 17x   42x   14x   28x   14x       14x   28x   14x 14x     17x   28x 28x   17x 17x   14x 14x   14x         17x 17x     14x           17x       17x   17x   17x   14x       3x                       21x 21x 21x   21x 21x   21x   15x     2x 2x 2x 2x   3x 3x     3x 3x   4x 4x     4x 4x   5x 5x           5x 5x   1x       21x   9x   12x   11x       1x         21x     21x   20x   1x   1x   1x       21x 21x   16x 16x   5x     5x           11x       21x   21x       21x   1x     49x                   1x   1x 1x 1x 1x 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 MongoStorage = require('../storage/MongoStorage');
 
/**
 * Search using mongodb query engine.
 * Requres ```mongodb``` package.
 */
class MongoSearch extends Search
{
  /**
   * @override
   */
  initialise(searchMeta, records)
  {
    const searchWeights = searchMeta.searchWeights || {};
    let collection = this.collection;
    return new Promise((resolve, reject) =>
    {
      function search()
      {
        let straight = {};
        let text = {};
        let textWeights = {};
        for (let field in searchMeta.fields)
        {
          if (searchMeta.fields[field].dummy)
          {
            continue;
          }
          if (searchMeta.fields[field].searchField)
          {
            straight[searchMeta.fields[field].searchField] = 1;
          }
          else
          {
            straight[field] = 1;
          }
          if (searchMeta.fields[field].filters.indexOf('search') !== -1)
          {
            text[field] = 'text';
            textWeights[field] = 1;
          }
        }
        for (let field in searchWeights)
        {
          text[field] = 'text';
          textWeights[field] = searchWeights[field];
        }
        let promises = [];
        for (let field in straight)
        {
          let f = {};
          f[field] = straight[field];
 
          promises.push(collection.createIndex(f, {
            background: true,
            name: field + '_straight'
          }));
        }
        console.log("INDEX", "TEXT", text, textWeights, "NORMAL", straight);
        if (Object.keys(text)
          .length > 0)
        {
          promises.push(collection.createIndex(text, {
            background: true,
            name: 'text',
            weights: textWeights
          }));
        }
        Promise.all(promises)
          .then(resolve, reject);
      }
      //resolve();
      collection.dropIndexes(() =>
      {
        collection.removeMany({}, () =>
        {
          if (records.length > 0)
          {
            collection.insertMany(records, {}, search);
          }
          else
          {
            search();
          }
        });
      });
    });
  }
 
  /**
   * @override
   */
  searchRecords(inquery, limit = 0)
  {
    const collection = this.collection;
    const primaryKey = this.primaryKey;
    return new Promise((resolve, reject) =>
    {
      let query = [],
        f, hasTextSearch = false;
 
      inquery.filter.forEach(infilter =>
      {
        switch (infilter.filter)
        {
        case 'equals':
          f = {};
          f[infilter.field] = infilter.value[0];
          query.push(f);
          break;
        case 'within':
          f = {};
          f[infilter.field] = {
            $in: infilter.value
          };
          query.push(f);
          break;
        case 'regex':
          f = {};
          f[infilter.field] = {
            $regex: infilter.value[0]
          };
          query.push(f);
          break;
        case 'search':
          hasTextSearch = true;
          f = {
            $text: {
              $search: infilter.value[0],
              $caseSensitive: false
            }
          };
          query.push(f);
          break;
        default:
          console.error('Unhandelled Filter', infilter);
        }
      });
 
      if (query.length === 0)
      {
        query = {};
      }
      else if (query.length === 1)
      {
        query = query[0];
      }
      else
      {
        query = {
          $and: query
        };
      }
 
      let project = {
        _id: 0
      };
      if (typeof primaryKey === 'string')
      {
        project[primaryKey] = 1;
      }
      else Eif (typeof primaryKey === 'object')
      {
        for (let key in primaryKey)
        {
          project[key] = 1;
        }
      }
 
      let sort = {};
      if (inquery.sort)
      {
        console.log(inquery.sort, hasTextSearch);
        if (inquery.sort === 'search' && hasTextSearch)
        {
          project.score = {
            $meta: "textScore"
          };
          sort.score = {
            $meta: "textScore"
          };
        }
        else
        {
          sort[inquery.sort] = inquery.order === 'dsc' ? -1 : 1;
        }
      }
 
      console.log('MONGO QUERY', query, 'PROJECT', project, 'SORT', sort);
 
      let search = collection.find(query)
        .project(project)
        .sort(sort);
 
      if (limit)
      {
        search = search.limit(limit);
      }
 
      search.map(x => (typeof primaryKey === 'string') ? x[primaryKey] : x)
        .toArray()
        .then(resolve, reject);
    });
  }
 
  // rest is the same as mongo storage
 
}
 
module.exports = MongoSearch;
 
MongoSearch.prototype.connect = MongoStorage.prototype.connect;
MongoSearch.prototype.createRecord = MongoStorage.prototype.createRecord;
MongoSearch.prototype.readRecord = MongoStorage.prototype.readRecord;
MongoSearch.prototype.updateRecord = MongoStorage.prototype.updateRecord;
MongoSearch.prototype.deleteRecord = MongoStorage.prototype.deleteRecord;