search.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. const match = uri.match(/^(https?:\/\/[^/]+)\/(.+)$/);
  89. if (match) {
  90. host = match[1];
  91. indexName = match[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. const 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. tag_names: page.tagNames,
  150. };
  151. document = Object.assign(document, generateDocContentsRelatedToRestriction(page));
  152. body.push(command);
  153. body.push({
  154. doc: document,
  155. doc_as_upsert: true,
  156. });
  157. };
  158. SearchClient.prototype.prepareBodyForCreate = function(body, page) {
  159. if (!Array.isArray(body)) {
  160. throw new Error('Body must be an array.');
  161. }
  162. const command = {
  163. index: {
  164. _index: this.indexName,
  165. _type: 'pages',
  166. _id: page._id.toString(),
  167. },
  168. };
  169. const bookmarkCount = page.bookmarkCount || 0;
  170. let document = {
  171. path: page.path,
  172. body: page.revision.body,
  173. username: page.creator.username,
  174. comment_count: page.commentCount,
  175. bookmark_count: bookmarkCount,
  176. like_count: page.liker.length || 0,
  177. created_at: page.createdAt,
  178. updated_at: page.updatedAt,
  179. tag_names: page.tagNames,
  180. };
  181. document = Object.assign(document, generateDocContentsRelatedToRestriction(page));
  182. body.push(command);
  183. body.push(document);
  184. };
  185. SearchClient.prototype.prepareBodyForDelete = function(body, page) {
  186. if (!Array.isArray(body)) {
  187. throw new Error('Body must be an array.');
  188. }
  189. const command = {
  190. delete: {
  191. _index: this.indexName,
  192. _type: 'pages',
  193. _id: page._id.toString(),
  194. },
  195. };
  196. body.push(command);
  197. };
  198. SearchClient.prototype.addPages = async function(pages) {
  199. const Bookmark = this.crowi.model('Bookmark');
  200. const PageTagRelation = this.crowi.model('PageTagRelation');
  201. const body = [];
  202. /* eslint-disable no-await-in-loop */
  203. for (const page of pages) {
  204. page.bookmarkCount = await Bookmark.countByPageId(page._id);
  205. const tagRelations = await PageTagRelation.find({ relatedPage: page._id }).populate('relatedTag');
  206. page.tagNames = tagRelations.map((relation) => { return relation.relatedTag.name });
  207. this.prepareBodyForCreate(body, page);
  208. }
  209. /* eslint-enable no-await-in-loop */
  210. logger.debug('addPages(): Sending Request to ES', body);
  211. return this.client.bulk({
  212. body,
  213. });
  214. };
  215. SearchClient.prototype.updatePages = async function(pages) {
  216. const self = this;
  217. const PageTagRelation = this.crowi.model('PageTagRelation');
  218. const body = [];
  219. /* eslint-disable no-await-in-loop */
  220. for (const page of pages) {
  221. const tagRelations = await PageTagRelation.find({ relatedPage: page._id }).populate('relatedTag');
  222. page.tagNames = tagRelations.map((relation) => { return relation.relatedTag.name });
  223. self.prepareBodyForUpdate(body, page);
  224. }
  225. logger.debug('updatePages(): Sending Request to ES', body);
  226. return this.client.bulk({
  227. body,
  228. });
  229. };
  230. SearchClient.prototype.deletePages = function(pages) {
  231. const self = this;
  232. const body = [];
  233. pages.map((page) => {
  234. self.prepareBodyForDelete(body, page);
  235. return;
  236. });
  237. logger.debug('deletePages(): Sending Request to ES', body);
  238. return this.client.bulk({
  239. body,
  240. });
  241. };
  242. SearchClient.prototype.addAllPages = async function() {
  243. const self = this;
  244. const Page = this.crowi.model('Page');
  245. const allPageCount = await Page.allPageCount();
  246. const Bookmark = this.crowi.model('Bookmark');
  247. const PageTagRelation = this.crowi.model('PageTagRelation');
  248. const cursor = Page.getStreamOfFindAll();
  249. let body = [];
  250. let sent = 0;
  251. let skipped = 0;
  252. let total = 0;
  253. return new Promise((resolve, reject) => {
  254. const bulkSend = (body) => {
  255. self.client
  256. .bulk({
  257. body,
  258. requestTimeout: Infinity,
  259. })
  260. .then((res) => {
  261. logger.info('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took, 'ms');
  262. })
  263. .catch((err) => {
  264. logger.error('addAllPages error on add anyway: ', err);
  265. });
  266. };
  267. cursor
  268. .eachAsync(async(doc) => {
  269. if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
  270. // debug('Skipped', doc.path);
  271. skipped++;
  272. return;
  273. }
  274. total++;
  275. const bookmarkCount = await Bookmark.countByPageId(doc._id);
  276. const tagRelations = await PageTagRelation.find({ relatedPage: doc._id }).populate('relatedTag');
  277. const page = { ...doc, bookmarkCount, tagNames: tagRelations.map((relation) => { return relation.relatedTag.name }) };
  278. self.prepareBodyForCreate(body, page);
  279. if (body.length >= 4000) {
  280. // send each 2000 docs. (body has 2 elements for each data)
  281. sent++;
  282. logger.debug('Sending request (seq, total, skipped)', sent, total, skipped);
  283. bulkSend(body);
  284. this.searchEvent.emit('addPageProgress', allPageCount, total, skipped);
  285. body = [];
  286. }
  287. })
  288. .then(() => {
  289. // send all remaining data on body[]
  290. logger.debug('Sending last body of bulk operation:', body.length);
  291. bulkSend(body);
  292. this.searchEvent.emit('finishAddPage', allPageCount, total, skipped);
  293. resolve();
  294. })
  295. .catch((e) => {
  296. logger.error('Error wile iterating cursor.eachAsync()', e);
  297. reject(e);
  298. });
  299. });
  300. };
  301. /**
  302. * search returning type:
  303. * {
  304. * meta: { total: Integer, results: Integer},
  305. * data: [ pages ...],
  306. * }
  307. */
  308. SearchClient.prototype.search = async function(query) {
  309. // for debug
  310. if (process.env.NODE_ENV === 'development') {
  311. const result = await this.client.indices.validateQuery({
  312. explain: true,
  313. body: {
  314. query: query.body.query,
  315. },
  316. });
  317. logger.debug('ES returns explanations: ', result.explanations);
  318. }
  319. const result = await this.client.search(query);
  320. // for debug
  321. logger.debug('ES result: ', result);
  322. return {
  323. meta: {
  324. took: result.took,
  325. total: result.hits.total,
  326. results: result.hits.hits.length,
  327. },
  328. data: result.hits.hits.map((elm) => {
  329. return { _id: elm._id, _score: elm._score, _source: elm._source };
  330. }),
  331. };
  332. };
  333. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option) {
  334. // getting path by default is almost for debug
  335. let fields = ['path', 'bookmark_count'];
  336. if (option) {
  337. fields = option.fields || fields;
  338. }
  339. // default is only id field, sorted by updated_at
  340. const query = {
  341. index: this.indexName,
  342. type: 'pages',
  343. body: {
  344. sort: [{ updated_at: { order: 'desc' } }],
  345. query: {}, // query
  346. _source: fields,
  347. },
  348. };
  349. this.appendResultSize(query);
  350. return query;
  351. };
  352. SearchClient.prototype.createSearchQuerySortedByScore = function(option) {
  353. let fields = ['path', 'bookmark_count'];
  354. if (option) {
  355. fields = option.fields || fields;
  356. }
  357. // sort by score
  358. const query = {
  359. index: this.indexName,
  360. type: 'pages',
  361. body: {
  362. sort: [{ _score: { order: 'desc' } }],
  363. query: {}, // query
  364. _source: fields,
  365. },
  366. };
  367. this.appendResultSize(query);
  368. return query;
  369. };
  370. SearchClient.prototype.appendResultSize = function(query, from, size) {
  371. query.from = from || this.DEFAULT_OFFSET;
  372. query.size = size || this.DEFAULT_LIMIT;
  373. };
  374. SearchClient.prototype.initializeBoolQuery = function(query) {
  375. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  376. if (!query.body.query.bool) {
  377. query.body.query.bool = {};
  378. }
  379. const isInitialized = (query) => { return !!query && Array.isArray(query) };
  380. if (!isInitialized(query.body.query.bool.filter)) {
  381. query.body.query.bool.filter = [];
  382. }
  383. if (!isInitialized(query.body.query.bool.must)) {
  384. query.body.query.bool.must = [];
  385. }
  386. if (!isInitialized(query.body.query.bool.must_not)) {
  387. query.body.query.bool.must_not = [];
  388. }
  389. return query;
  390. };
  391. SearchClient.prototype.appendCriteriaForQueryString = function(query, queryString) {
  392. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  393. // parse
  394. const parsedKeywords = this.parseQueryString(queryString);
  395. if (parsedKeywords.match.length > 0) {
  396. const q = {
  397. multi_match: {
  398. query: parsedKeywords.match.join(' '),
  399. type: 'most_fields',
  400. fields: ['path.ja^2', 'path.en^2', 'body.ja', 'body.en'],
  401. },
  402. };
  403. query.body.query.bool.must.push(q);
  404. }
  405. if (parsedKeywords.not_match.length > 0) {
  406. const q = {
  407. multi_match: {
  408. query: parsedKeywords.not_match.join(' '),
  409. fields: ['path.ja', 'path.en', 'body.ja', 'body.en'],
  410. operator: 'or',
  411. },
  412. };
  413. query.body.query.bool.must_not.push(q);
  414. }
  415. if (parsedKeywords.phrase.length > 0) {
  416. const phraseQueries = [];
  417. parsedKeywords.phrase.forEach((phrase) => {
  418. phraseQueries.push({
  419. multi_match: {
  420. query: phrase, // each phrase is quoteted words
  421. type: 'phrase',
  422. fields: [
  423. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  424. 'path.raw^2',
  425. 'body',
  426. ],
  427. },
  428. });
  429. });
  430. query.body.query.bool.must.push(phraseQueries);
  431. }
  432. if (parsedKeywords.not_phrase.length > 0) {
  433. const notPhraseQueries = [];
  434. parsedKeywords.not_phrase.forEach((phrase) => {
  435. notPhraseQueries.push({
  436. multi_match: {
  437. query: phrase, // each phrase is quoteted words
  438. type: 'phrase',
  439. fields: [
  440. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  441. 'path.raw^2',
  442. 'body',
  443. ],
  444. },
  445. });
  446. });
  447. query.body.query.bool.must_not.push(notPhraseQueries);
  448. }
  449. if (parsedKeywords.prefix.length > 0) {
  450. const queries = parsedKeywords.prefix.map((path) => {
  451. return { prefix: { 'path.raw': path } };
  452. });
  453. query.body.query.bool.filter.push({ bool: { should: queries } });
  454. }
  455. if (parsedKeywords.not_prefix.length > 0) {
  456. const queries = parsedKeywords.not_prefix.map((path) => {
  457. return { prefix: { 'path.raw': path } };
  458. });
  459. query.body.query.bool.filter.push({ bool: { must_not: queries } });
  460. }
  461. };
  462. SearchClient.prototype.filterPagesByViewer = async function(query, user, userGroups) {
  463. const Config = this.crowi.model('Config');
  464. const config = this.crowi.getConfig();
  465. const showPagesRestrictedByOwner = !Config.hidePagesRestrictedByOwnerInList(config);
  466. const showPagesRestrictedByGroup = !Config.hidePagesRestrictedByGroupInList(config);
  467. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  468. const Page = this.crowi.model('Page');
  469. const {
  470. GRANT_PUBLIC, GRANT_RESTRICTED, GRANT_SPECIFIED, GRANT_OWNER, GRANT_USER_GROUP,
  471. } = Page;
  472. const grantConditions = [
  473. { term: { grant: GRANT_PUBLIC } },
  474. ];
  475. // ensure to hit to GRANT_RESTRICTED pages that the user specified at own
  476. if (user != null) {
  477. grantConditions.push(
  478. {
  479. bool: {
  480. must: [
  481. { term: { grant: GRANT_RESTRICTED } },
  482. { term: { granted_users: user._id.toString() } },
  483. ],
  484. },
  485. },
  486. );
  487. }
  488. if (showPagesRestrictedByOwner) {
  489. grantConditions.push(
  490. { term: { grant: GRANT_SPECIFIED } },
  491. { term: { grant: GRANT_OWNER } },
  492. );
  493. }
  494. else if (user != null) {
  495. grantConditions.push(
  496. {
  497. bool: {
  498. must: [
  499. { term: { grant: GRANT_SPECIFIED } },
  500. { term: { granted_users: user._id.toString() } },
  501. ],
  502. },
  503. },
  504. {
  505. bool: {
  506. must: [
  507. { term: { grant: GRANT_OWNER } },
  508. { term: { granted_users: user._id.toString() } },
  509. ],
  510. },
  511. },
  512. );
  513. }
  514. if (showPagesRestrictedByGroup) {
  515. grantConditions.push(
  516. { term: { grant: GRANT_USER_GROUP } },
  517. );
  518. }
  519. else if (userGroups != null && userGroups.length > 0) {
  520. const userGroupIds = userGroups.map((group) => { return group._id.toString() });
  521. grantConditions.push(
  522. {
  523. bool: {
  524. must: [
  525. { term: { grant: GRANT_USER_GROUP } },
  526. { terms: { granted_group: userGroupIds } },
  527. ],
  528. },
  529. },
  530. );
  531. }
  532. query.body.query.bool.filter.push({ bool: { should: grantConditions } });
  533. };
  534. SearchClient.prototype.filterPortalPages = function(query) {
  535. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  536. query.body.query.bool.must_not.push(this.queries.USER);
  537. query.body.query.bool.filter.push(this.queries.PORTAL);
  538. };
  539. SearchClient.prototype.filterPublicPages = function(query) {
  540. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  541. query.body.query.bool.must_not.push(this.queries.USER);
  542. query.body.query.bool.filter.push(this.queries.PUBLIC);
  543. };
  544. SearchClient.prototype.filterUserPages = function(query) {
  545. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  546. query.body.query.bool.filter.push(this.queries.USER);
  547. };
  548. SearchClient.prototype.filterPagesByType = function(query, type) {
  549. const Page = this.crowi.model('Page');
  550. switch (type) {
  551. case Page.TYPE_PORTAL:
  552. return this.filterPortalPages(query);
  553. case Page.TYPE_PUBLIC:
  554. return this.filterPublicPages(query);
  555. case Page.TYPE_USER:
  556. return this.filterUserPages(query);
  557. default:
  558. return query;
  559. }
  560. };
  561. SearchClient.prototype.appendFunctionScore = function(query, queryString) {
  562. const User = this.crowi.model('User');
  563. const count = User.count({}) || 1;
  564. const minScore = queryString.length * 0.1 - 1; // increase with length
  565. logger.debug('min_score: ', minScore);
  566. query.body.query = {
  567. function_score: {
  568. query: { ...query.body.query },
  569. // // disable min_score -- 2019.02.28 Yuki Takei
  570. // // more precise adjustment is needed...
  571. // min_score: minScore,
  572. field_value_factor: {
  573. field: 'bookmark_count',
  574. modifier: 'log1p',
  575. factor: 10000 / count,
  576. missing: 0,
  577. },
  578. boost_mode: 'sum',
  579. },
  580. };
  581. };
  582. SearchClient.prototype.searchKeyword = async function(queryString, user, userGroups, option) {
  583. const from = option.offset || null;
  584. const size = option.limit || null;
  585. const type = option.type || null;
  586. const query = this.createSearchQuerySortedByScore();
  587. this.appendCriteriaForQueryString(query, queryString);
  588. this.filterPagesByType(query, type);
  589. await this.filterPagesByViewer(query, user, userGroups);
  590. this.appendResultSize(query, from, size);
  591. this.appendFunctionScore(query, queryString);
  592. return this.search(query);
  593. };
  594. SearchClient.prototype.parseQueryString = function(queryString) {
  595. const matchWords = [];
  596. const notMatchWords = [];
  597. const phraseWords = [];
  598. const notPhraseWords = [];
  599. const prefixPaths = [];
  600. const notPrefixPaths = [];
  601. queryString.trim();
  602. queryString = queryString.replace(/\s+/g, ' '); // eslint-disable-line no-param-reassign
  603. // First: Parse phrase keywords
  604. const phraseRegExp = new RegExp(/(-?"[^"]+")/g);
  605. const phrases = queryString.match(phraseRegExp);
  606. if (phrases !== null) {
  607. queryString = queryString.replace(phraseRegExp, ''); // eslint-disable-line no-param-reassign
  608. phrases.forEach((phrase) => {
  609. phrase.trim();
  610. if (phrase.match(/^-/)) {
  611. notPhraseWords.push(phrase.replace(/^-/, ''));
  612. }
  613. else {
  614. phraseWords.push(phrase);
  615. }
  616. });
  617. }
  618. // Second: Parse other keywords (include minus keywords)
  619. queryString.split(' ').forEach((word) => {
  620. if (word === '') {
  621. return;
  622. }
  623. // https://regex101.com/r/lN4LIV/1
  624. const matchNegative = word.match(/^-(prefix:)?(.+)$/);
  625. // https://regex101.com/r/gVssZe/1
  626. const matchPositive = word.match(/^(prefix:)?(.+)$/);
  627. if (matchNegative != null) {
  628. const isPrefixCondition = (matchNegative[1] != null);
  629. if (isPrefixCondition) {
  630. notPrefixPaths.push(matchNegative[2]);
  631. }
  632. else {
  633. notMatchWords.push(matchNegative[2]);
  634. }
  635. }
  636. else if (matchPositive != null) {
  637. const isPrefixCondition = (matchPositive[1] != null);
  638. if (isPrefixCondition) {
  639. prefixPaths.push(matchPositive[2]);
  640. }
  641. else {
  642. matchWords.push(matchPositive[2]);
  643. }
  644. }
  645. });
  646. return {
  647. match: matchWords,
  648. not_match: notMatchWords,
  649. phrase: phraseWords,
  650. not_phrase: notPhraseWords,
  651. prefix: prefixPaths,
  652. not_prefix: notPrefixPaths,
  653. };
  654. };
  655. SearchClient.prototype.syncPageCreated = function(page, user, bookmarkCount = 0) {
  656. debug('SearchClient.syncPageCreated', page.path);
  657. if (!this.shouldIndexed(page)) {
  658. return;
  659. }
  660. page.bookmarkCount = bookmarkCount;
  661. this.addPages([page])
  662. .then((res) => {
  663. debug('ES Response', res);
  664. })
  665. .catch((err) => {
  666. logger.error('ES Error', err);
  667. });
  668. };
  669. SearchClient.prototype.syncPageUpdated = function(page, user, bookmarkCount = 0) {
  670. debug('SearchClient.syncPageUpdated', page.path);
  671. // TODO delete
  672. if (!this.shouldIndexed(page)) {
  673. this.deletePages([page])
  674. .then((res) => {
  675. debug('deletePages: ES Response', res);
  676. })
  677. .catch((err) => {
  678. logger.error('deletePages:ES Error', err);
  679. });
  680. return;
  681. }
  682. page.bookmarkCount = bookmarkCount;
  683. this.updatePages([page])
  684. .then((res) => {
  685. debug('ES Response', res);
  686. })
  687. .catch((err) => {
  688. logger.error('ES Error', err);
  689. });
  690. };
  691. SearchClient.prototype.syncPageDeleted = function(page, user) {
  692. debug('SearchClient.syncPageDeleted', page.path);
  693. this.deletePages([page])
  694. .then((res) => {
  695. debug('deletePages: ES Response', res);
  696. })
  697. .catch((err) => {
  698. logger.error('deletePages:ES Error', err);
  699. });
  700. };
  701. SearchClient.prototype.syncBookmarkChanged = async function(pageId) {
  702. const Page = this.crowi.model('Page');
  703. const Bookmark = this.crowi.model('Bookmark');
  704. const page = await Page.findById(pageId);
  705. const bookmarkCount = await Bookmark.countByPageId(pageId);
  706. page.bookmarkCount = bookmarkCount;
  707. this.updatePages([page])
  708. .then((res) => { return debug('ES Response', res) })
  709. .catch((err) => { return logger.error('ES Error', err) });
  710. };
  711. module.exports = SearchClient;