search.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 offset = 0;
  171. var Page = this.crowi.model('Page');
  172. var cursor = Page.getStreamOfFindAll();
  173. var body = [];
  174. var sent = 0;
  175. var skipped = 0;
  176. var counter = 0;
  177. return new Promise(function(resolve, reject) {
  178. cursor.on('data', function (doc) {
  179. if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
  180. //debug('Skipped', doc.path);
  181. skipped++;
  182. return ;
  183. }
  184. self.prepareBodyForCreate(body, doc);
  185. //debug(body.length);
  186. if (body.length > 2000) {
  187. sent++;
  188. debug('Sending request (seq, skipped)', sent, skipped);
  189. self.client.bulk({
  190. body: body,
  191. requestTimeout: Infinity,
  192. }).then(res => {
  193. debug('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took)
  194. }).catch(err => {
  195. debug('addAllPages error on add anyway: ', err)
  196. });
  197. body = [];
  198. }
  199. }).on('error', function (err) {
  200. // TODO: handle err
  201. debug('Error cursor:', err);
  202. }).on('close', function () {
  203. // all done
  204. // 最後にすべてを送信
  205. debug('Sending last body of bulk operation:', body.length)
  206. self.client.bulk({
  207. body: body,
  208. requestTimeout: Infinity,
  209. })
  210. .then(function(res) {
  211. debug('Reponse from es (item length, errros, took):', (res.items || []).length, res.errors, res.took);
  212. return resolve(res);
  213. }).catch(function(err) {
  214. debug('Err from es:', err);
  215. return reject(err);
  216. });
  217. });
  218. });
  219. };
  220. /**
  221. * search returning type:
  222. * {
  223. * meta: { total: Integer, results: Integer},
  224. * data: [ pages ...],
  225. * }
  226. */
  227. SearchClient.prototype.search = function(query)
  228. {
  229. var self = this;
  230. return new Promise(function(resolve, reject) {
  231. self.client.search(query)
  232. .then(function(data) {
  233. var result = {
  234. meta: {
  235. took: data.took,
  236. total: data.hits.total,
  237. results: data.hits.hits.length,
  238. },
  239. data: data.hits.hits.map(function(elm) {
  240. return {_id: elm._id, _score: elm._score};
  241. })
  242. };
  243. resolve(result);
  244. }).catch(function(err) {
  245. reject(err);
  246. });
  247. });
  248. };
  249. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option)
  250. {
  251. // getting path by default is almost for debug
  252. var fields = ['path'];
  253. if (option) {
  254. fields = option.fields || fields;
  255. }
  256. // default is only id field, sorted by updated_at
  257. var query = {
  258. index: this.index_name,
  259. type: 'pages',
  260. body: {
  261. sort: [{ updated_at: { order: 'desc'}}],
  262. query: {}, // query
  263. _source: fields,
  264. }
  265. };
  266. this.appendResultSize(query);
  267. return query;
  268. };
  269. SearchClient.prototype.createSearchQuerySortedByScore = function(option)
  270. {
  271. var fields = ['path'];
  272. if (option) {
  273. fields = option.fields || fields;
  274. }
  275. // sort by score
  276. var query = {
  277. index: this.index_name,
  278. type: 'pages',
  279. body: {
  280. sort: [ {_score: { order: 'desc'} }],
  281. query: {}, // query
  282. _source: fields,
  283. }
  284. };
  285. this.appendResultSize(query);
  286. return query;
  287. };
  288. SearchClient.prototype.appendResultSize = function(query, from, size)
  289. {
  290. query.from = from || this.DEFAULT_OFFSET;
  291. query.size = size || this.DEFAULT_LIMIT;
  292. };
  293. SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword)
  294. {
  295. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  296. if (!query.body.query.bool) {
  297. query.body.query.bool = {};
  298. }
  299. if (!query.body.query.bool.must || !Array.isArray(query.body.query.must)) {
  300. query.body.query.bool.must = [];
  301. }
  302. if (!query.body.query.bool.must_not || !Array.isArray(query.body.query.must_not)) {
  303. query.body.query.bool.must_not = [];
  304. }
  305. var appendMultiMatchQuery = function(query, type, keywords) {
  306. var target;
  307. var operator = 'and';
  308. switch (type) {
  309. case 'not_match':
  310. target = query.body.query.bool.must_not;
  311. operator = 'or';
  312. break;
  313. case 'match':
  314. default:
  315. target = query.body.query.bool.must;
  316. }
  317. target.push({
  318. multi_match: {
  319. query: keywords.join(' '),
  320. // TODO: By user's i18n setting, change boost or search target fields
  321. fields: [
  322. "path_ja^2",
  323. "body_ja",
  324. // "path_en",
  325. // "body_en",
  326. ],
  327. operator: operator,
  328. }
  329. });
  330. return query;
  331. };
  332. var parsedKeywords = this.getParsedKeywords(keyword);
  333. if (parsedKeywords.match.length > 0) {
  334. query = appendMultiMatchQuery(query, 'match', parsedKeywords.match);
  335. }
  336. if (parsedKeywords.not_match.length > 0) {
  337. query = appendMultiMatchQuery(query, 'not_match', parsedKeywords.not_match);
  338. }
  339. if (parsedKeywords.phrase.length > 0) {
  340. var phraseQueries = [];
  341. parsedKeywords.phrase.forEach(function(phrase) {
  342. phraseQueries.push({
  343. multi_match: {
  344. query: phrase, // each phrase is quoteted words
  345. type: 'phrase',
  346. fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
  347. "path_raw^2",
  348. "body_raw",
  349. ],
  350. }
  351. });
  352. });
  353. query.body.query.bool.must.push(phraseQueries);
  354. }
  355. if (parsedKeywords.not_phrase.length > 0) {
  356. var notPhraseQueries = [];
  357. parsedKeywords.not_phrase.forEach(function(phrase) {
  358. notPhraseQueries.push({
  359. multi_match: {
  360. query: phrase, // each phrase is quoteted words
  361. type: 'phrase',
  362. fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words
  363. "path_raw^2",
  364. "body_raw",
  365. ],
  366. }
  367. });
  368. });
  369. query.body.query.bool.must_not.push(notPhraseQueries);
  370. }
  371. };
  372. SearchClient.prototype.appendCriteriaForPathFilter = function(query, path)
  373. {
  374. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  375. if (!query.body.query.bool) {
  376. query.body.query.bool = {};
  377. }
  378. if (!query.body.query.bool.filter || !Array.isArray(query.body.query.bool.filter)) {
  379. query.body.query.bool.filter = [];
  380. }
  381. if (path.match(/\/$/)) {
  382. path = path.substr(0, path.length - 1);
  383. }
  384. query.body.query.bool.filter.push({
  385. wildcard: {
  386. "path": path + "/*"
  387. }
  388. });
  389. };
  390. SearchClient.prototype.searchKeyword = function(keyword, option)
  391. {
  392. var from = option.offset || null;
  393. var query = this.createSearchQuerySortedByScore();
  394. this.appendCriteriaForKeywordContains(query, keyword);
  395. return this.search(query);
  396. };
  397. SearchClient.prototype.searchByPath = function(keyword, prefix)
  398. {
  399. // TODO path 名だけから検索
  400. };
  401. SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option)
  402. {
  403. var from = option.offset || null;
  404. var query = this.createSearchQuerySortedByScore();
  405. this.appendCriteriaForKeywordContains(query, keyword);
  406. this.appendCriteriaForPathFilter(query, path);
  407. if (from) {
  408. this.appendResultSize(query, from);
  409. }
  410. return this.search(query);
  411. };
  412. SearchClient.prototype.getParsedKeywords = function(keyword)
  413. {
  414. var matchWords = [];
  415. var notMatchWords = [];
  416. var phraseWords = [];
  417. var notPhraseWords = [];
  418. keyword.trim();
  419. keyword = keyword.replace(/\s+/g, ' ');
  420. // First: Parse phrase keywords
  421. var phraseRegExp = new RegExp(/(-?"[^"]+")/g);
  422. var phrases = keyword.match(phraseRegExp);
  423. if (phrases !== null) {
  424. keyword = keyword.replace(phraseRegExp, '');
  425. phrases.forEach(function(phrase) {
  426. phrase.trim();
  427. if (phrase.match(/^\-/)) {
  428. notPhraseWords.push(phrase.replace(/^\-/, ''));
  429. } else {
  430. phraseWords.push(phrase);
  431. }
  432. });
  433. }
  434. // Second: Parse other keywords (include minus keywords)
  435. keyword.split(' ').forEach(function(word) {
  436. if (word === '') {
  437. return;
  438. }
  439. if (word.match(/^\-(.+)$/)) {
  440. notMatchWords.push((RegExp.$1));
  441. } else {
  442. matchWords.push(word);
  443. }
  444. });
  445. return {
  446. match: matchWords,
  447. not_match: notMatchWords,
  448. phrase: phraseWords,
  449. not_phrase: notPhraseWords,
  450. };
  451. }
  452. SearchClient.prototype.syncPageCreated = function(page, user)
  453. {
  454. debug('SearchClient.syncPageCreated', page.path);
  455. if (!this.shouldIndexed(page)) {
  456. return ;
  457. }
  458. this.addPages([page])
  459. .then(function(res) {
  460. debug('ES Response', res);
  461. })
  462. .catch(function(err){
  463. debug('ES Error', err);
  464. });
  465. };
  466. SearchClient.prototype.syncPageUpdated = function(page, user)
  467. {
  468. debug('SearchClient.syncPageUpdated', page.path);
  469. // TODO delete
  470. if (!this.shouldIndexed(page)) {
  471. this.deletePages([page])
  472. .then(function(res) {
  473. debug('deletePages: ES Response', res);
  474. })
  475. .catch(function(err){
  476. debug('deletePages:ES Error', err);
  477. });
  478. return ;
  479. }
  480. this.updatePages([page])
  481. .then(function(res) {
  482. debug('ES Response', res);
  483. })
  484. .catch(function(err){
  485. debug('ES Error', err);
  486. });
  487. };
  488. SearchClient.prototype.syncPageDeleted = function(page, user)
  489. {
  490. debug('SearchClient.syncPageDeleted', page.path);
  491. this.deletePages([page])
  492. .then(function(res) {
  493. debug('deletePages: ES Response', res);
  494. })
  495. .catch(function(err){
  496. debug('deletePages:ES Error', err);
  497. });
  498. return ;
  499. };
  500. module.exports = SearchClient;