search.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. /**
  2. * Search
  3. */
  4. const elasticsearch = require('elasticsearch');
  5. const debug = require('debug')('growi:lib:search');
  6. const logger = require('@alias/logger')('growi:lib:search');
  7. function SearchClient(crowi, esUri) {
  8. this.DEFAULT_OFFSET = 0;
  9. this.DEFAULT_LIMIT = 50;
  10. this.esNodeName = '-';
  11. this.esNodeNames = [];
  12. this.esVersion = 'unknown';
  13. this.esVersions = [];
  14. this.esPlugin = [];
  15. this.esPlugins = [];
  16. this.esUri = esUri;
  17. this.crowi = crowi;
  18. this.searchEvent = crowi.event('search');
  19. // In Elasticsearch RegExp, we don't need to used ^ and $.
  20. // Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-regexp-query.html#_standard_operators
  21. this.queries = {
  22. PORTAL: {
  23. regexp: {
  24. 'path.raw': '.*/',
  25. },
  26. },
  27. PUBLIC: {
  28. regexp: {
  29. 'path.raw': '.*[^/]',
  30. },
  31. },
  32. USER: {
  33. prefix: {
  34. 'path.raw': '/user/',
  35. },
  36. },
  37. };
  38. const uri = this.parseUri(this.esUri);
  39. this.host = uri.host;
  40. this.indexName = uri.indexName;
  41. this.client = new elasticsearch.Client({
  42. host: this.host,
  43. requestTimeout: 5000,
  44. // log: 'debug',
  45. });
  46. this.registerUpdateEvent();
  47. this.mappingFile = crowi.resourceDir + 'search/mappings.json';
  48. }
  49. SearchClient.prototype.getInfo = function() {
  50. return this.client.info({});
  51. };
  52. SearchClient.prototype.checkESVersion = async function() {
  53. try {
  54. const nodes = await this.client.nodes.info();
  55. if (!nodes._nodes || !nodes.nodes) {
  56. throw new Error('no nodes info');
  57. }
  58. for (const [nodeName, nodeInfo] of Object.entries(nodes.nodes)) {
  59. this.esNodeName = nodeName;
  60. this.esNodeNames.push(nodeName);
  61. this.esVersion = nodeInfo.version;
  62. this.esVersions.push(nodeInfo.version);
  63. this.esPlugin = nodeInfo.plugins;
  64. this.esPlugins.push(nodeInfo.plugins);
  65. }
  66. }
  67. catch (error) {
  68. logger.error('es check version error:', error);
  69. }
  70. };
  71. SearchClient.prototype.registerUpdateEvent = function() {
  72. const pageEvent = this.crowi.event('page');
  73. pageEvent.on('create', this.syncPageCreated.bind(this));
  74. pageEvent.on('update', this.syncPageUpdated.bind(this));
  75. pageEvent.on('delete', this.syncPageDeleted.bind(this));
  76. const bookmarkEvent = this.crowi.event('bookmark');
  77. bookmarkEvent.on('create', this.syncBookmarkChanged.bind(this));
  78. bookmarkEvent.on('delete', this.syncBookmarkChanged.bind(this));
  79. };
  80. SearchClient.prototype.shouldIndexed = function(page) {
  81. return (page.redirectTo == null);
  82. };
  83. // BONSAI_URL is following format:
  84. // => https://{ID}:{PASSWORD}@{HOST}
  85. SearchClient.prototype.parseUri = function(uri) {
  86. let indexName = 'crowi';
  87. let host = uri;
  88. let m;
  89. if ((m = uri.match(/^(https?:\/\/[^/]+)\/(.+)$/))) {
  90. host = m[1];
  91. indexName = m[2];
  92. }
  93. return {
  94. host,
  95. indexName,
  96. };
  97. };
  98. SearchClient.prototype.buildIndex = function(uri) {
  99. return this.client.indices.create({
  100. index: this.indexName,
  101. body: require(this.mappingFile),
  102. });
  103. };
  104. SearchClient.prototype.deleteIndex = function(uri) {
  105. return this.client.indices.delete({
  106. index: this.indexName,
  107. });
  108. };
  109. /**
  110. * generate object that is related to page.grant*
  111. */
  112. function generateDocContentsRelatedToRestriction(page) {
  113. let grantedUserIds = null;
  114. if (page.grantedUsers != null && page.grantedUsers.length > 0) {
  115. grantedUserIds = page.grantedUsers.map(user => {
  116. const userId = (user._id == null) ? user : user._id;
  117. return userId.toString();
  118. });
  119. }
  120. let grantedGroupId = null;
  121. if (page.grantedGroup != null) {
  122. const groupId = (page.grantedGroup._id == null) ? page.grantedGroup : page.grantedGroup._id;
  123. grantedGroupId = groupId.toString();
  124. }
  125. return {
  126. grant: page.grant,
  127. granted_users: grantedUserIds,
  128. granted_group: grantedGroupId,
  129. };
  130. }
  131. SearchClient.prototype.prepareBodyForUpdate = function(body, page) {
  132. if (!Array.isArray(body)) {
  133. throw new Error('Body must be an array.');
  134. }
  135. let command = {
  136. update: {
  137. _index: this.indexName,
  138. _type: 'pages',
  139. _id: page._id.toString(),
  140. },
  141. };
  142. let document = {
  143. path: page.path,
  144. body: page.revision.body,
  145. comment_count: page.commentCount,
  146. bookmark_count: page.bookmarkCount || 0,
  147. like_count: page.liker.length || 0,
  148. updated_at: page.updatedAt,
  149. };
  150. document = Object.assign(document, generateDocContentsRelatedToRestriction(page));
  151. body.push(command);
  152. body.push({
  153. doc: document,
  154. doc_as_upsert: true,
  155. });
  156. };
  157. SearchClient.prototype.prepareBodyForCreate = function(body, page) {
  158. if (!Array.isArray(body)) {
  159. throw new Error('Body must be an array.');
  160. }
  161. let command = {
  162. index: {
  163. _index: this.indexName,
  164. _type: 'pages',
  165. _id: page._id.toString(),
  166. },
  167. };
  168. const bookmarkCount = page.bookmarkCount || 0;
  169. let document = {
  170. path: page.path,
  171. body: page.revision.body,
  172. username: page.creator.username,
  173. comment_count: page.commentCount,
  174. bookmark_count: bookmarkCount,
  175. like_count: page.liker.length || 0,
  176. created_at: page.createdAt,
  177. updated_at: page.updatedAt,
  178. };
  179. document = Object.assign(document, generateDocContentsRelatedToRestriction(page));
  180. body.push(command);
  181. body.push(document);
  182. };
  183. SearchClient.prototype.prepareBodyForDelete = function(body, page) {
  184. if (!Array.isArray(body)) {
  185. throw new Error('Body must be an array.');
  186. }
  187. let command = {
  188. delete: {
  189. _index: this.indexName,
  190. _type: 'pages',
  191. _id: page._id.toString(),
  192. },
  193. };
  194. body.push(command);
  195. };
  196. SearchClient.prototype.addPages = async function(pages) {
  197. const Bookmark = this.crowi.model('Bookmark');
  198. const body = [];
  199. for (const page of pages) {
  200. page.bookmarkCount = await Bookmark.countByPageId(page._id);
  201. this.prepareBodyForCreate(body, page);
  202. }
  203. logger.debug('addPages(): Sending Request to ES', body);
  204. return this.client.bulk({
  205. body: body,
  206. });
  207. };
  208. SearchClient.prototype.updatePages = function(pages) {
  209. let self = this;
  210. let body = [];
  211. pages.map(function(page) {
  212. self.prepareBodyForUpdate(body, page);
  213. });
  214. logger.debug('updatePages(): Sending Request to ES', body);
  215. return this.client.bulk({
  216. body: body,
  217. });
  218. };
  219. SearchClient.prototype.deletePages = function(pages) {
  220. let self = this;
  221. let body = [];
  222. pages.map(function(page) {
  223. self.prepareBodyForDelete(body, page);
  224. });
  225. logger.debug('deletePages(): Sending Request to ES', body);
  226. return this.client.bulk({
  227. body: body,
  228. });
  229. };
  230. SearchClient.prototype.addAllPages = async function() {
  231. const self = this;
  232. const Page = this.crowi.model('Page');
  233. const allPageCount = await Page.allPageCount();
  234. const Bookmark = this.crowi.model('Bookmark');
  235. const cursor = Page.getStreamOfFindAll();
  236. let body = [];
  237. let sent = 0;
  238. let skipped = 0;
  239. let total = 0;
  240. return new Promise((resolve, reject) => {
  241. const bulkSend = body => {
  242. self.client
  243. .bulk({
  244. body: body,
  245. requestTimeout: Infinity,
  246. })
  247. .then(res => {
  248. logger.info('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took, 'ms');
  249. })
  250. .catch(err => {
  251. logger.error('addAllPages error on add anyway: ', err);
  252. });
  253. };
  254. cursor
  255. .eachAsync(async doc => {
  256. if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
  257. // debug('Skipped', doc.path);
  258. skipped++;
  259. return;
  260. }
  261. total++;
  262. const bookmarkCount = await Bookmark.countByPageId(doc._id);
  263. const page = { ...doc, bookmarkCount };
  264. self.prepareBodyForCreate(body, page);
  265. if (body.length >= 4000) {
  266. // send each 2000 docs. (body has 2 elements for each data)
  267. sent++;
  268. logger.debug('Sending request (seq, total, skipped)', sent, total, skipped);
  269. bulkSend(body);
  270. this.searchEvent.emit('addPageProgress', allPageCount, total, skipped);
  271. body = [];
  272. }
  273. })
  274. .then(() => {
  275. // send all remaining data on body[]
  276. logger.debug('Sending last body of bulk operation:', body.length);
  277. bulkSend(body);
  278. this.searchEvent.emit('finishAddPage', allPageCount, total, skipped);
  279. resolve();
  280. })
  281. .catch(e => {
  282. logger.error('Error wile iterating cursor.eachAsync()', e);
  283. reject(e);
  284. });
  285. });
  286. };
  287. /**
  288. * search returning type:
  289. * {
  290. * meta: { total: Integer, results: Integer},
  291. * data: [ pages ...],
  292. * }
  293. */
  294. SearchClient.prototype.search = async function(query) {
  295. // for debug
  296. if (process.env.NODE_ENV === 'development') {
  297. const result = await this.client.indices.validateQuery({
  298. explain: true,
  299. body: {
  300. query: query.body.query
  301. },
  302. });
  303. logger.info('ES returns explanations: ', result.explanations);
  304. }
  305. const result = await this.client.search(query);
  306. return {
  307. meta: {
  308. took: result.took,
  309. total: result.hits.total,
  310. results: result.hits.hits.length,
  311. },
  312. data: result.hits.hits.map(function(elm) {
  313. return { _id: elm._id, _score: elm._score, _source: elm._source };
  314. }),
  315. };
  316. };
  317. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option) {
  318. // getting path by default is almost for debug
  319. let fields = ['path', 'bookmark_count'];
  320. if (option) {
  321. fields = option.fields || fields;
  322. }
  323. // default is only id field, sorted by updated_at
  324. let query = {
  325. index: this.indexName,
  326. type: 'pages',
  327. body: {
  328. sort: [{ updated_at: { order: 'desc' } }],
  329. query: {}, // query
  330. _source: fields,
  331. },
  332. };
  333. this.appendResultSize(query);
  334. return query;
  335. };
  336. SearchClient.prototype.createSearchQuerySortedByScore = function(option) {
  337. let fields = ['path', 'bookmark_count'];
  338. if (option) {
  339. fields = option.fields || fields;
  340. }
  341. // sort by score
  342. let query = {
  343. index: this.indexName,
  344. type: 'pages',
  345. body: {
  346. sort: [{ _score: { order: 'desc' } }],
  347. query: {}, // query
  348. _source: fields,
  349. },
  350. };
  351. this.appendResultSize(query);
  352. return query;
  353. };
  354. SearchClient.prototype.appendResultSize = function(query, from, size) {
  355. query.from = from || this.DEFAULT_OFFSET;
  356. query.size = size || this.DEFAULT_LIMIT;
  357. };
  358. SearchClient.prototype.initializeBoolQuery = function(query) {
  359. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  360. if (!query.body.query.bool) {
  361. query.body.query.bool = {};
  362. }
  363. const isInitialized = query => !!query && Array.isArray(query);
  364. if (!isInitialized(query.body.query.bool.filter)) {
  365. query.body.query.bool.filter = [];
  366. }
  367. if (!isInitialized(query.body.query.bool.must)) {
  368. query.body.query.bool.must = [];
  369. }
  370. if (!isInitialized(query.body.query.bool.must_not)) {
  371. query.body.query.bool.must_not = [];
  372. }
  373. return query;
  374. };
  375. SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword) {
  376. query = this.initializeBoolQuery(query);
  377. const appendMultiMatchQuery = function(query, type, keywords) {
  378. let target;
  379. let operator = 'and';
  380. switch (type) {
  381. case 'not_match':
  382. target = query.body.query.bool.must_not;
  383. operator = 'or';
  384. break;
  385. case 'match':
  386. default:
  387. target = query.body.query.bool.must;
  388. }
  389. target.push({
  390. multi_match: {
  391. query: keywords.join(' '),
  392. // TODO: By user's i18n setting, change boost or search target fields
  393. fields: ['path.ja^2', 'path.en^2', 'body.ja', 'body.en'],
  394. operator: operator,
  395. },
  396. });
  397. return query;
  398. };
  399. let parsedKeywords = this.getParsedKeywords(keyword);
  400. if (parsedKeywords.match.length > 0) {
  401. query = appendMultiMatchQuery(query, 'match', parsedKeywords.match);
  402. }
  403. if (parsedKeywords.not_match.length > 0) {
  404. query = appendMultiMatchQuery(query, 'not_match', parsedKeywords.not_match);
  405. }
  406. if (parsedKeywords.phrase.length > 0) {
  407. let phraseQueries = [];
  408. parsedKeywords.phrase.forEach(function(phrase) {
  409. phraseQueries.push({
  410. multi_match: {
  411. query: phrase, // each phrase is quoteted words
  412. type: 'phrase',
  413. fields: [
  414. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  415. 'path.raw^2',
  416. 'body',
  417. ],
  418. },
  419. });
  420. });
  421. query.body.query.bool.must.push(phraseQueries);
  422. }
  423. if (parsedKeywords.not_phrase.length > 0) {
  424. let notPhraseQueries = [];
  425. parsedKeywords.not_phrase.forEach(function(phrase) {
  426. notPhraseQueries.push({
  427. multi_match: {
  428. query: phrase, // each phrase is quoteted words
  429. type: 'phrase',
  430. fields: [
  431. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  432. 'path.raw^2',
  433. 'body',
  434. ],
  435. },
  436. });
  437. });
  438. query.body.query.bool.must_not.push(notPhraseQueries);
  439. }
  440. };
  441. SearchClient.prototype.appendCriteriaForPathFilter = function(query, path) {
  442. query = this.initializeBoolQuery(query);
  443. if (path.match(/\/$/)) {
  444. path = path.substr(0, path.length - 1);
  445. }
  446. query.body.query.bool.filter.push({
  447. wildcard: {
  448. 'path.raw': path + '/*',
  449. },
  450. });
  451. };
  452. SearchClient.prototype.filterPagesByViewer = async function(query, user, userGroups) {
  453. const Config = this.crowi.model('Config');
  454. const config = this.crowi.getConfig();
  455. // determine User condition
  456. const hidePagesRestrictedByOwner = Config.hidePagesRestrictedByOwnerInList(config);
  457. user = hidePagesRestrictedByOwner ? user : null;
  458. // determine UserGroup condition
  459. const hidePagesRestrictedByGroup = Config.hidePagesRestrictedByGroupInList(config);
  460. if (hidePagesRestrictedByGroup && user != null) {
  461. const UserGroupRelation = this.crowi.model('UserGroupRelation');
  462. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  463. }
  464. query = this.initializeBoolQuery(query);
  465. const Page = this.crowi.model('Page');
  466. const { GRANT_PUBLIC, GRANT_RESTRICTED, GRANT_SPECIFIED, GRANT_OWNER, GRANT_USER_GROUP } = Page;
  467. const grantConditions = [
  468. { term: { grant: GRANT_PUBLIC } },
  469. ];
  470. if (user == null) {
  471. grantConditions.push(
  472. { term: { grant: GRANT_RESTRICTED } },
  473. { term: { grant: GRANT_SPECIFIED } },
  474. { term: { grant: GRANT_OWNER } },
  475. );
  476. }
  477. else {
  478. grantConditions.push(
  479. { bool: {
  480. must: [
  481. { term: { grant: GRANT_RESTRICTED } },
  482. { term: { granted_users: user._id.toString() } }
  483. ]
  484. } },
  485. { bool: {
  486. must: [
  487. { term: { grant: GRANT_SPECIFIED } },
  488. { term: { granted_users: user._id.toString() } }
  489. ]
  490. } },
  491. { bool: {
  492. must: [
  493. { term: { grant: GRANT_OWNER } },
  494. { term: { granted_users: user._id.toString() } }
  495. ]
  496. } },
  497. );
  498. }
  499. if (userGroups == null) {
  500. grantConditions.push(
  501. { term: { grant: GRANT_USER_GROUP } },
  502. );
  503. }
  504. else if (userGroups.length > 0) {
  505. const userGroupIds = userGroups.map(group => group._id.toString() );
  506. grantConditions.push(
  507. { bool: {
  508. must: [
  509. { term: { grant: GRANT_USER_GROUP } },
  510. { terms: { granted_group: userGroupIds } }
  511. ]
  512. } },
  513. );
  514. }
  515. query.body.query.bool.filter.push({ bool: { should: grantConditions } });
  516. };
  517. SearchClient.prototype.filterPortalPages = function(query) {
  518. query = this.initializeBoolQuery(query);
  519. query.body.query.bool.must_not.push(this.queries.USER);
  520. query.body.query.bool.filter.push(this.queries.PORTAL);
  521. };
  522. SearchClient.prototype.filterPublicPages = function(query) {
  523. query = this.initializeBoolQuery(query);
  524. query.body.query.bool.must_not.push(this.queries.USER);
  525. query.body.query.bool.filter.push(this.queries.PUBLIC);
  526. };
  527. SearchClient.prototype.filterUserPages = function(query) {
  528. query = this.initializeBoolQuery(query);
  529. query.body.query.bool.filter.push(this.queries.USER);
  530. };
  531. SearchClient.prototype.filterPagesByType = function(query, type) {
  532. const Page = this.crowi.model('Page');
  533. switch (type) {
  534. case Page.TYPE_PORTAL:
  535. return this.filterPortalPages(query);
  536. case Page.TYPE_PUBLIC:
  537. return this.filterPublicPages(query);
  538. case Page.TYPE_USER:
  539. return this.filterUserPages(query);
  540. default:
  541. return query;
  542. }
  543. };
  544. SearchClient.prototype.appendFunctionScore = function(query) {
  545. const User = this.crowi.model('User');
  546. const count = User.count({}) || 1;
  547. // newScore = oldScore + log(1 + factor * 'bookmark_count')
  548. query.body.query = {
  549. function_score: {
  550. query: { ...query.body.query },
  551. field_value_factor: {
  552. field: 'bookmark_count',
  553. modifier: 'log1p',
  554. factor: 10000 / count,
  555. missing: 0,
  556. },
  557. boost_mode: 'sum',
  558. },
  559. };
  560. };
  561. SearchClient.prototype.searchKeyword = async function(keyword, user, userGroups, option) {
  562. const from = option.offset || null;
  563. const size = option.limit || null;
  564. const type = option.type || null;
  565. const query = this.createSearchQuerySortedByScore();
  566. this.appendCriteriaForKeywordContains(query, keyword);
  567. this.filterPagesByType(query, type);
  568. await this.filterPagesByViewer(query, user, userGroups);
  569. this.appendResultSize(query, from, size);
  570. this.appendFunctionScore(query);
  571. return this.search(query);
  572. };
  573. SearchClient.prototype.searchByPath = async function(keyword, prefix) {
  574. // TODO path 名だけから検索
  575. };
  576. SearchClient.prototype.searchKeywordUnderPath = async function(keyword, path, user, userGroups, option) {
  577. const from = option.offset || null;
  578. const size = option.limit || null;
  579. const type = option.type || null;
  580. const query = this.createSearchQuerySortedByScore();
  581. this.appendCriteriaForKeywordContains(query, keyword);
  582. this.appendCriteriaForPathFilter(query, path);
  583. this.filterPagesByType(query, type);
  584. await this.filterPagesByViewer(query, user, userGroups);
  585. this.appendResultSize(query, from, size);
  586. this.appendFunctionScore(query);
  587. return this.search(query);
  588. };
  589. SearchClient.prototype.getParsedKeywords = function(keyword) {
  590. let matchWords = [];
  591. let notMatchWords = [];
  592. let phraseWords = [];
  593. let notPhraseWords = [];
  594. keyword.trim();
  595. keyword = keyword.replace(/\s+/g, ' ');
  596. // First: Parse phrase keywords
  597. let phraseRegExp = new RegExp(/(-?"[^"]+")/g);
  598. let phrases = keyword.match(phraseRegExp);
  599. if (phrases !== null) {
  600. keyword = keyword.replace(phraseRegExp, '');
  601. phrases.forEach(function(phrase) {
  602. phrase.trim();
  603. if (phrase.match(/^-/)) {
  604. notPhraseWords.push(phrase.replace(/^-/, ''));
  605. }
  606. else {
  607. phraseWords.push(phrase);
  608. }
  609. });
  610. }
  611. // Second: Parse other keywords (include minus keywords)
  612. keyword.split(' ').forEach(function(word) {
  613. if (word === '') {
  614. return;
  615. }
  616. if (word.match(/^-(.+)$/)) {
  617. notMatchWords.push(RegExp.$1);
  618. }
  619. else {
  620. matchWords.push(word);
  621. }
  622. });
  623. return {
  624. match: matchWords,
  625. not_match: notMatchWords,
  626. phrase: phraseWords,
  627. not_phrase: notPhraseWords,
  628. };
  629. };
  630. SearchClient.prototype.syncPageCreated = function(page, user, bookmarkCount = 0) {
  631. debug('SearchClient.syncPageCreated', page.path);
  632. if (!this.shouldIndexed(page)) {
  633. return;
  634. }
  635. page.bookmarkCount = bookmarkCount;
  636. this.addPages([page])
  637. .then(function(res) {
  638. debug('ES Response', res);
  639. })
  640. .catch(function(err) {
  641. logger.error('ES Error', err);
  642. });
  643. };
  644. SearchClient.prototype.syncPageUpdated = function(page, user, bookmarkCount = 0) {
  645. debug('SearchClient.syncPageUpdated', page.path);
  646. // TODO delete
  647. if (!this.shouldIndexed(page)) {
  648. this.deletePages([page])
  649. .then(function(res) {
  650. debug('deletePages: ES Response', res);
  651. })
  652. .catch(function(err) {
  653. logger.error('deletePages:ES Error', err);
  654. });
  655. return;
  656. }
  657. page.bookmarkCount = bookmarkCount;
  658. this.updatePages([page])
  659. .then(function(res) {
  660. debug('ES Response', res);
  661. })
  662. .catch(function(err) {
  663. logger.error('ES Error', err);
  664. });
  665. };
  666. SearchClient.prototype.syncPageDeleted = function(page, user) {
  667. debug('SearchClient.syncPageDeleted', page.path);
  668. this.deletePages([page])
  669. .then(function(res) {
  670. debug('deletePages: ES Response', res);
  671. })
  672. .catch(function(err) {
  673. logger.error('deletePages:ES Error', err);
  674. });
  675. };
  676. SearchClient.prototype.syncBookmarkChanged = async function(pageId) {
  677. const Page = this.crowi.model('Page');
  678. const Bookmark = this.crowi.model('Bookmark');
  679. const page = await Page.findPageById(pageId);
  680. const bookmarkCount = await Bookmark.countByPageId(pageId);
  681. page.bookmarkCount = bookmarkCount;
  682. this.updatePages([page])
  683. .then(res => debug('ES Response', res))
  684. .catch(err => logger.error('ES Error', err));
  685. };
  686. module.exports = SearchClient;