search.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /**
  2. * Search
  3. */
  4. var elasticsearch = require('elasticsearch'),
  5. debug = require('debug')('crowi:lib:search');
  6. function SearchClient(crowi, esUri) {
  7. this.DEFAULT_OFFSET = 0;
  8. this.DEFAULT_LIMIT = 50;
  9. this.esUri = esUri;
  10. this.crowi = crowi;
  11. var uri = this.parseUri(this.esUri);
  12. this.host = uri.host;
  13. this.index_name = uri.index_name;
  14. this.client = new elasticsearch.Client({
  15. host: this.host,
  16. requestTimeout: 5000,
  17. //log: 'debug',
  18. });
  19. this.registerUpdateEvent();
  20. this.mappingFile = crowi.resourceDir + 'search/mappings.json';
  21. }
  22. SearchClient.prototype.checkESVersion = function() {
  23. // TODO
  24. };
  25. SearchClient.prototype.registerUpdateEvent = function() {
  26. var pageEvent = this.crowi.event('page');
  27. pageEvent.on('create', this.syncPageCreated.bind(this))
  28. pageEvent.on('update', this.syncPageUpdated.bind(this))
  29. pageEvent.on('delete', this.syncPageDeleted.bind(this))
  30. };
  31. SearchClient.prototype.shouldIndexed = function(page) {
  32. // FIXME: Magic Number
  33. if (page.grant !== 1) {
  34. return false;
  35. }
  36. if (page.redirectTo !== null) {
  37. return false;
  38. }
  39. if (page.isDeleted()) {
  40. return false;
  41. }
  42. return true;
  43. };
  44. // BONSAI_URL is following format:
  45. // => https://{ID}:{PASSWORD}@{HOST}
  46. SearchClient.prototype.parseUri = function(uri) {
  47. var index_name = 'crowi';
  48. var host = uri;
  49. if (m = uri.match(/^(https?:\/\/[^\/]+)\/(.+)$/)) {
  50. host = m[1];
  51. index_name = m[2];
  52. }
  53. return {
  54. host,
  55. index_name,
  56. };
  57. };
  58. SearchClient.prototype.buildIndex = function(uri) {
  59. return this.client.indices.create({
  60. index: this.index_name,
  61. body: require(this.mappingFile)
  62. });
  63. };
  64. SearchClient.prototype.deleteIndex = function(uri) {
  65. return this.client.indices.delete({
  66. index: this.index_name,
  67. });
  68. };
  69. SearchClient.prototype.prepareBodyForUpdate = function(body, page) {
  70. if (!Array.isArray(body)) {
  71. throw new Error('Body must be an array.');
  72. }
  73. var command = {
  74. update: {
  75. _index: this.index_name,
  76. _type: 'pages',
  77. _id: page._id.toString(),
  78. }
  79. };
  80. var document = {
  81. doc: {
  82. path: page.path,
  83. body: page.revision.body,
  84. comment_count: page.commentCount,
  85. bookmark_count: 0, // todo
  86. like_count: page.liker.length || 0,
  87. updated_at: page.updatedAt,
  88. },
  89. doc_as_upsert: true,
  90. };
  91. body.push(command);
  92. body.push(document);
  93. };
  94. SearchClient.prototype.prepareBodyForCreate = function(body, page) {
  95. if (!Array.isArray(body)) {
  96. throw new Error('Body must be an array.');
  97. }
  98. var command = {
  99. index: {
  100. _index: this.index_name,
  101. _type: 'pages',
  102. _id: page._id.toString(),
  103. }
  104. };
  105. var document = {
  106. path: page.path,
  107. body: page.revision.body,
  108. username: page.creator.username,
  109. comment_count: page.commentCount,
  110. bookmark_count: 0, // todo
  111. like_count: page.liker.length || 0,
  112. created_at: page.createdAt,
  113. updated_at: page.updatedAt,
  114. };
  115. body.push(command);
  116. body.push(document);
  117. };
  118. SearchClient.prototype.prepareBodyForDelete = function(body, page) {
  119. if (!Array.isArray(body)) {
  120. throw new Error('Body must be an array.');
  121. }
  122. var command = {
  123. delete: {
  124. _index: this.index_name,
  125. _type: 'pages',
  126. _id: page._id.toString(),
  127. }
  128. };
  129. body.push(command);
  130. };
  131. SearchClient.prototype.addPages = function(pages)
  132. {
  133. var self = this;
  134. var body = [];
  135. pages.map(function(page) {
  136. self.prepareBodyForCreate(body, page);
  137. });
  138. debug('addPages(): Sending Request to ES', body);
  139. return this.client.bulk({
  140. body: body,
  141. });
  142. };
  143. SearchClient.prototype.updatePages = function(pages)
  144. {
  145. var self = this;
  146. var body = [];
  147. pages.map(function(page) {
  148. self.prepareBodyForUpdate(body, page);
  149. });
  150. debug('updatePages(): Sending Request to ES', body);
  151. return this.client.bulk({
  152. body: body,
  153. });
  154. };
  155. SearchClient.prototype.deletePages = function(pages)
  156. {
  157. var self = this;
  158. var body = [];
  159. pages.map(function(page) {
  160. self.prepareBodyForDelete(body, page);
  161. });
  162. debug('deletePages(): Sending Request to ES', body);
  163. return this.client.bulk({
  164. body: body,
  165. });
  166. };
  167. SearchClient.prototype.addAllPages = function()
  168. {
  169. var self = this;
  170. var Page = this.crowi.model('Page');
  171. var cursor = Page.getStreamOfFindAll();
  172. var body = [];
  173. return new Promise(function(resolve, reject) {
  174. cursor.on('data', function (doc) {
  175. if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
  176. debug('Skipped', doc.path);
  177. return ;
  178. }
  179. self.prepareBodyForCreate(body, doc);
  180. }).on('error', function (err) {
  181. // TODO: handle err
  182. debug('Error cursor:', err);
  183. }).on('close', function () {
  184. // all done
  185. // return if body is empty
  186. // see: https://github.com/weseek/crowi-plus/issues/228
  187. if (body.length == 0) {
  188. return resolve();
  189. }
  190. // 最後に送信
  191. self.client.bulk({
  192. body: body,
  193. requestTimeout: Infinity,
  194. })
  195. .then(function(res) {
  196. debug('Reponse from es:', res);
  197. return resolve(res);
  198. }).catch(function(err) {
  199. debug('Err from es:', err);
  200. return reject(err);
  201. });
  202. });
  203. });
  204. };
  205. /**
  206. * search returning type:
  207. * {
  208. * meta: { total: Integer, results: Integer},
  209. * data: [ pages ...],
  210. * }
  211. */
  212. SearchClient.prototype.search = function(query)
  213. {
  214. var self = this;
  215. return new Promise(function(resolve, reject) {
  216. self.client.search(query)
  217. .then(function(data) {
  218. var result = {
  219. meta: {
  220. took: data.took,
  221. total: data.hits.total,
  222. results: data.hits.hits.length,
  223. },
  224. data: data.hits.hits.map(function(elm) {
  225. return {_id: elm._id, _score: elm._score};
  226. })
  227. };
  228. resolve(result);
  229. }).catch(function(err) {
  230. reject(err);
  231. });
  232. });
  233. };
  234. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option)
  235. {
  236. // getting path by default is almost for debug
  237. var fields = ['path'];
  238. if (option) {
  239. fields = option.fields || fields;
  240. }
  241. // default is only id field, sorted by updated_at
  242. var query = {
  243. index: this.index_name,
  244. type: 'pages',
  245. body: {
  246. sort: [{ updated_at: { order: 'desc'}}],
  247. query: {}, // query
  248. _source: fields,
  249. }
  250. };
  251. this.appendResultSize(query);
  252. return query;
  253. };
  254. SearchClient.prototype.createSearchQuerySortedByScore = function(option)
  255. {
  256. var fields = ['path'];
  257. if (option) {
  258. fields = option.fields || fields;
  259. }
  260. // sort by score
  261. var query = {
  262. index: this.index_name,
  263. type: 'pages',
  264. body: {
  265. sort: [ {_score: { order: 'desc'} }],
  266. query: {}, // query
  267. _source: fields,
  268. }
  269. };
  270. this.appendResultSize(query);
  271. return query;
  272. };
  273. SearchClient.prototype.appendResultSize = function(query, from, size)
  274. {
  275. query.from = from || this.DEFAULT_OFFSET;
  276. query.size = size || this.DEFAULT_LIMIT;
  277. };
  278. SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword)
  279. {
  280. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  281. if (!query.body.query.bool) {
  282. query.body.query.bool = {};
  283. }
  284. if (!query.body.query.bool.must || !Array.isArray(query.body.query.must)) {
  285. query.body.query.bool.must = [];
  286. }
  287. if (!query.body.query.bool.must_not || !Array.isArray(query.body.query.must_not)) {
  288. query.body.query.bool.must_not = [];
  289. }
  290. var appendMultiMatchQuery = function(query, type, keywords) {
  291. var target;
  292. var operator = 'and';
  293. switch (type) {
  294. case 'not_match':
  295. target = query.body.query.bool.must_not;
  296. operator = 'or';
  297. break;
  298. case 'match':
  299. default:
  300. target = query.body.query.bool.must;
  301. }
  302. target.push({
  303. multi_match: {
  304. query: keywords.join(' '),
  305. // TODO: By user's i18n setting, change boost or search target fields
  306. fields: [
  307. "path_ja^2",
  308. "path_en^2",
  309. "body_ja",
  310. // "path_en",
  311. // "body_en",
  312. ],
  313. operator: operator,
  314. }
  315. });
  316. return query;
  317. };
  318. var parsedKeywords = this.getParsedKeywords(keyword);
  319. if (parsedKeywords.match.length > 0) {
  320. query = appendMultiMatchQuery(query, 'match', parsedKeywords.match);
  321. }
  322. if (parsedKeywords.not_match.length > 0) {
  323. query = appendMultiMatchQuery(query, 'not_match', parsedKeywords.not_match);
  324. }
  325. if (parsedKeywords.phrase.length > 0) {
  326. var phraseQueries = [];
  327. parsedKeywords.phrase.forEach(function(phrase) {
  328. phraseQueries.push({
  329. multi_match: {
  330. query: phrase, // each phrase is quoteted words
  331. type: 'phrase',
  332. fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
  333. "path_raw^2",
  334. "body_raw",
  335. ],
  336. }
  337. });
  338. });
  339. query.body.query.bool.must.push(phraseQueries);
  340. }
  341. if (parsedKeywords.not_phrase.length > 0) {
  342. var notPhraseQueries = [];
  343. parsedKeywords.not_phrase.forEach(function(phrase) {
  344. notPhraseQueries.push({
  345. multi_match: {
  346. query: phrase, // each phrase is quoteted words
  347. type: 'phrase',
  348. fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
  349. "path_raw^2",
  350. "body_raw",
  351. ],
  352. }
  353. });
  354. });
  355. query.body.query.bool.must_not.push(notPhraseQueries);
  356. }
  357. };
  358. SearchClient.prototype.appendCriteriaForPathFilter = function(query, path)
  359. {
  360. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  361. if (!query.body.query.bool) {
  362. query.body.query.bool = {};
  363. }
  364. if (!query.body.query.bool.filter || !Array.isArray(query.body.query.bool.filter)) {
  365. query.body.query.bool.filter = [];
  366. }
  367. if (path.match(/\/$/)) {
  368. path = path.substr(0, path.length - 1);
  369. }
  370. query.body.query.bool.filter.push({
  371. wildcard: {
  372. "path": path + "/*"
  373. }
  374. });
  375. };
  376. SearchClient.prototype.searchKeyword = function(keyword, option)
  377. {
  378. var from = option.offset || null;
  379. var query = this.createSearchQuerySortedByScore();
  380. this.appendCriteriaForKeywordContains(query, keyword);
  381. return this.search(query);
  382. };
  383. SearchClient.prototype.searchByPath = function(keyword, prefix)
  384. {
  385. // TODO path 名だけから検索
  386. };
  387. SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option)
  388. {
  389. var from = option.offset || null;
  390. var query = this.createSearchQuerySortedByScore();
  391. this.appendCriteriaForKeywordContains(query, keyword);
  392. this.appendCriteriaForPathFilter(query, path);
  393. if (from) {
  394. this.appendResultSize(query, from);
  395. }
  396. return this.search(query);
  397. };
  398. SearchClient.prototype.getParsedKeywords = function(keyword)
  399. {
  400. var matchWords = [];
  401. var notMatchWords = [];
  402. var phraseWords = [];
  403. var notPhraseWords = [];
  404. keyword.trim();
  405. keyword = keyword.replace(/\s+/g, ' ');
  406. // First: Parse phrase keywords
  407. var phraseRegExp = new RegExp(/(-?"[^"]+")/g);
  408. var phrases = keyword.match(phraseRegExp);
  409. if (phrases !== null) {
  410. keyword = keyword.replace(phraseRegExp, '');
  411. phrases.forEach(function(phrase) {
  412. phrase.trim();
  413. if (phrase.match(/^\-/)) {
  414. notPhraseWords.push(phrase.replace(/^\-/, ''));
  415. } else {
  416. phraseWords.push(phrase);
  417. }
  418. });
  419. }
  420. // Second: Parse other keywords (include minus keywords)
  421. keyword.split(' ').forEach(function(word) {
  422. if (word === '') {
  423. return;
  424. }
  425. if (word.match(/^\-(.+)$/)) {
  426. notMatchWords.push((RegExp.$1));
  427. } else {
  428. matchWords.push(word);
  429. }
  430. });
  431. return {
  432. match: matchWords,
  433. not_match: notMatchWords,
  434. phrase: phraseWords,
  435. not_phrase: notPhraseWords,
  436. };
  437. }
  438. SearchClient.prototype.syncPageCreated = function(page, user)
  439. {
  440. debug('SearchClient.syncPageCreated', page.path);
  441. if (!this.shouldIndexed(page)) {
  442. return ;
  443. }
  444. this.addPages([page])
  445. .then(function(res) {
  446. debug('ES Response', res);
  447. })
  448. .catch(function(err){
  449. debug('ES Error', err);
  450. });
  451. };
  452. SearchClient.prototype.syncPageUpdated = function(page, user)
  453. {
  454. debug('SearchClient.syncPageUpdated', page.path);
  455. // TODO delete
  456. if (!this.shouldIndexed(page)) {
  457. this.deletePages([page])
  458. .then(function(res) {
  459. debug('deletePages: ES Response', res);
  460. })
  461. .catch(function(err){
  462. debug('deletePages:ES Error', err);
  463. });
  464. return ;
  465. }
  466. this.updatePages([page])
  467. .then(function(res) {
  468. debug('ES Response', res);
  469. })
  470. .catch(function(err){
  471. debug('ES Error', err);
  472. });
  473. };
  474. SearchClient.prototype.syncPageDeleted = function(page, user)
  475. {
  476. debug('SearchClient.syncPageDeleted', page.path);
  477. this.deletePages([page])
  478. .then(function(res) {
  479. debug('deletePages: ES Response', res);
  480. })
  481. .catch(function(err){
  482. debug('deletePages:ES Error', err);
  483. });
  484. return ;
  485. };
  486. module.exports = SearchClient;