search.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. "use strict";
  2. const Promise = require('bluebird'),
  3. _ = require('lodash'),
  4. path = require('path');
  5. /**
  6. * Search Model
  7. */
  8. module.exports = {
  9. _si: null,
  10. /**
  11. * Initialize Search model
  12. *
  13. * @param {Object} appconfig The application config
  14. * @return {Object} Search model instance
  15. */
  16. init(appconfig) {
  17. let self = this;
  18. return self;
  19. },
  20. find(terms) {
  21. let self = this;
  22. terms = _.chain(terms)
  23. .deburr()
  24. .toLower()
  25. .trim()
  26. .replace(/[^a-z0-9 ]/g, '')
  27. .split(' ')
  28. .filter((f) => { return !_.isEmpty(f); })
  29. .join(' ')
  30. .value();
  31. return db.Entry.find(
  32. { $text: { $search: terms } },
  33. { score: { $meta: "textScore" }, title: 1 }
  34. )
  35. .sort({ score: { $meta: "textScore" } })
  36. .limit(10)
  37. .exec()
  38. .then((hits) => {
  39. /*if(hits.length < 5) {
  40. return self._si.matchAsync({
  41. beginsWith: terms,
  42. threshold: 3,
  43. limit: 5,
  44. type: 'simple'
  45. }).then((matches) => {
  46. return {
  47. match: hits,
  48. suggest: matches
  49. };
  50. });
  51. } else {*/
  52. return {
  53. match: hits,
  54. suggest: []
  55. };
  56. //}
  57. }).catch((err) => {
  58. if(err.type === 'NotFoundError') {
  59. return {
  60. match: [],
  61. suggest: []
  62. };
  63. } else {
  64. winston.error(err);
  65. }
  66. });
  67. },
  68. /**
  69. * Delete an entry from the index
  70. *
  71. * @param {String} The entry path
  72. * @return {Promise} Promise of the operation
  73. */
  74. delete(entryPath) {
  75. let self = this;
  76. /*let hasResults = false;
  77. return new Promise((resolve, reject) => {
  78. self._si.search({
  79. query: {
  80. AND: { 'entryPath': [entryPath] }
  81. }
  82. }).on('data', (results) => {
  83. hasResults = true;
  84. if(results.totalHits > 0) {
  85. let delIds = _.map(results.hits, 'id');
  86. self._si.del(delIds).on('end', () => { return resolve(true); });
  87. } else {
  88. resolve(true);
  89. }
  90. }).on('error', (err) => {
  91. if(err.type === 'NotFoundError') {
  92. resolve(true);
  93. } else {
  94. winston.error(err);
  95. reject(err);
  96. }
  97. }).on('end', () => {
  98. if(!hasResults) {
  99. resolve(true);
  100. }
  101. });
  102. });*/
  103. }
  104. };