search.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  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. const {
  8. Writable, Transform,
  9. } = require('stream');
  10. const streamToPromise = require('stream-to-promise');
  11. const { createBatchStream } = require('./batch-stream');
  12. const BULK_REINDEX_SIZE = 100;
  13. function SearchClient(crowi, esUri) {
  14. this.DEFAULT_OFFSET = 0;
  15. this.DEFAULT_LIMIT = 50;
  16. this.esNodeName = '-';
  17. this.esNodeNames = [];
  18. this.esVersion = 'unknown';
  19. this.esVersions = [];
  20. this.esPlugin = [];
  21. this.esPlugins = [];
  22. this.esUri = esUri;
  23. this.crowi = crowi;
  24. this.searchEvent = crowi.event('search');
  25. this.configManager = this.crowi.configManager;
  26. // In Elasticsearch RegExp, we don't need to used ^ and $.
  27. // Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-regexp-query.html#_standard_operators
  28. this.queries = {
  29. PORTAL: {
  30. regexp: {
  31. 'path.raw': '.*/',
  32. },
  33. },
  34. PUBLIC: {
  35. regexp: {
  36. 'path.raw': '.*[^/]',
  37. },
  38. },
  39. USER: {
  40. prefix: {
  41. 'path.raw': '/user/',
  42. },
  43. },
  44. };
  45. const uri = this.parseUri(this.esUri);
  46. this.host = uri.host;
  47. this.indexName = uri.indexName;
  48. this.aliasName = `${this.indexName}-alias`;
  49. this.client = new elasticsearch.Client({
  50. host: this.host,
  51. requestTimeout: 5000,
  52. // log: 'debug',
  53. });
  54. this.registerUpdateEvent();
  55. this.mappingFile = `${crowi.resourceDir}search/mappings.json`;
  56. }
  57. SearchClient.prototype.getInfo = function() {
  58. return this.client.info({});
  59. };
  60. SearchClient.prototype.checkESVersion = async function() {
  61. try {
  62. const nodes = await this.client.nodes.info();
  63. if (!nodes._nodes || !nodes.nodes) {
  64. throw new Error('no nodes info');
  65. }
  66. for (const [nodeName, nodeInfo] of Object.entries(nodes.nodes)) {
  67. this.esNodeName = nodeName;
  68. this.esNodeNames.push(nodeName);
  69. this.esVersion = nodeInfo.version;
  70. this.esVersions.push(nodeInfo.version);
  71. this.esPlugin = nodeInfo.plugins;
  72. this.esPlugins.push(nodeInfo.plugins);
  73. }
  74. }
  75. catch (error) {
  76. logger.error('es check version error:', error);
  77. }
  78. };
  79. SearchClient.prototype.registerUpdateEvent = function() {
  80. const pageEvent = this.crowi.event('page');
  81. pageEvent.on('create', this.syncPageUpdated.bind(this));
  82. pageEvent.on('update', this.syncPageUpdated.bind(this));
  83. pageEvent.on('delete', this.syncPageDeleted.bind(this));
  84. const bookmarkEvent = this.crowi.event('bookmark');
  85. bookmarkEvent.on('create', this.syncBookmarkChanged.bind(this));
  86. bookmarkEvent.on('delete', this.syncBookmarkChanged.bind(this));
  87. const tagEvent = this.crowi.event('tag');
  88. tagEvent.on('update', this.syncTagChanged.bind(this));
  89. };
  90. SearchClient.prototype.shouldIndexed = function(page) {
  91. return page.creator != null && page.revision != null && page.redirectTo == null;
  92. };
  93. SearchClient.prototype.parseUri = function(uri) {
  94. let indexName = 'crowi';
  95. let host = uri;
  96. // https://regex101.com/r/eKT4Db/4
  97. const match = uri.match(/^(https?:\/\/[^/]+)\/?(.+)?$/);
  98. if (match) {
  99. host = match[1];
  100. indexName = match[2] || 'growi';
  101. }
  102. return {
  103. host,
  104. indexName,
  105. };
  106. };
  107. SearchClient.prototype.initIndices = async function() {
  108. await this.checkESVersion();
  109. const { client, indexName, aliasName } = this;
  110. const tmpIndexName = `${indexName}-tmp`;
  111. // remove tmp index
  112. const isExistsTmpIndex = await client.indices.exists({ index: tmpIndexName });
  113. if (isExistsTmpIndex) {
  114. await client.indices.delete({ index: tmpIndexName });
  115. }
  116. // create index
  117. const isExistsIndex = await client.indices.exists({ index: indexName });
  118. if (!isExistsIndex) {
  119. await this.createIndex(indexName);
  120. }
  121. // create alias
  122. const isExistsAlias = await client.indices.existsAlias({ name: aliasName, index: indexName });
  123. if (!isExistsAlias) {
  124. await client.indices.putAlias({
  125. name: aliasName,
  126. index: indexName,
  127. });
  128. }
  129. };
  130. SearchClient.prototype.createIndex = async function(index) {
  131. const body = require(this.mappingFile);
  132. return this.client.indices.create({ index, body });
  133. };
  134. SearchClient.prototype.buildIndex = async function(uri) {
  135. await this.initIndices();
  136. const { client, indexName } = this;
  137. const aliasName = `${indexName}-alias`;
  138. const tmpIndexName = `${indexName}-tmp`;
  139. // reindex to tmp index
  140. await this.createIndex(tmpIndexName);
  141. await client.reindex({
  142. waitForCompletion: false,
  143. body: {
  144. source: { index: indexName },
  145. dest: { index: tmpIndexName },
  146. },
  147. });
  148. // update alias
  149. await client.indices.updateAliases({
  150. body: {
  151. actions: [
  152. { add: { alias: aliasName, index: tmpIndexName } },
  153. { remove: { alias: aliasName, index: indexName } },
  154. ],
  155. },
  156. });
  157. // flush index
  158. await client.indices.delete({
  159. index: indexName,
  160. });
  161. await this.createIndex(indexName);
  162. await this.addAllPages();
  163. // update alias
  164. await client.indices.updateAliases({
  165. body: {
  166. actions: [
  167. { add: { alias: aliasName, index: indexName } },
  168. { remove: { alias: aliasName, index: tmpIndexName } },
  169. ],
  170. },
  171. });
  172. // remove tmp index
  173. await client.indices.delete({ index: tmpIndexName });
  174. };
  175. /**
  176. * generate object that is related to page.grant*
  177. */
  178. function generateDocContentsRelatedToRestriction(page) {
  179. let grantedUserIds = null;
  180. if (page.grantedUsers != null && page.grantedUsers.length > 0) {
  181. grantedUserIds = page.grantedUsers.map((user) => {
  182. const userId = (user._id == null) ? user : user._id;
  183. return userId.toString();
  184. });
  185. }
  186. let grantedGroupId = null;
  187. if (page.grantedGroup != null) {
  188. const groupId = (page.grantedGroup._id == null) ? page.grantedGroup : page.grantedGroup._id;
  189. grantedGroupId = groupId.toString();
  190. }
  191. return {
  192. grant: page.grant,
  193. granted_users: grantedUserIds,
  194. granted_group: grantedGroupId,
  195. };
  196. }
  197. SearchClient.prototype.prepareBodyForCreate = function(body, page) {
  198. if (!Array.isArray(body)) {
  199. throw new Error('Body must be an array.');
  200. }
  201. const command = {
  202. index: {
  203. _index: this.indexName,
  204. _type: 'pages',
  205. _id: page._id.toString(),
  206. },
  207. };
  208. const bookmarkCount = page.bookmarkCount || 0;
  209. let document = {
  210. path: page.path,
  211. body: page.revision.body,
  212. username: page.creator.username,
  213. comment_count: page.commentCount,
  214. bookmark_count: bookmarkCount,
  215. like_count: page.liker.length || 0,
  216. created_at: page.createdAt,
  217. updated_at: page.updatedAt,
  218. tag_names: page.tagNames,
  219. };
  220. document = Object.assign(document, generateDocContentsRelatedToRestriction(page));
  221. body.push(command);
  222. body.push(document);
  223. };
  224. SearchClient.prototype.prepareBodyForDelete = function(body, page) {
  225. if (!Array.isArray(body)) {
  226. throw new Error('Body must be an array.');
  227. }
  228. const command = {
  229. delete: {
  230. _index: this.indexName,
  231. _type: 'pages',
  232. _id: page._id.toString(),
  233. },
  234. };
  235. body.push(command);
  236. };
  237. SearchClient.prototype.addAllPages = async function() {
  238. const Page = this.crowi.model('Page');
  239. return this.updateOrInsertPages(() => Page.find(), true);
  240. };
  241. SearchClient.prototype.updateOrInsertPageById = async function(pageId) {
  242. const Page = this.crowi.model('Page');
  243. return this.updateOrInsertPages(() => Page.findById(pageId));
  244. };
  245. /**
  246. * @param {function} queryFactory factory method to generate a Mongoose Query instance
  247. */
  248. SearchClient.prototype.updateOrInsertPages = async function(queryFactory, isEmittingProgressEvent = false) {
  249. const Page = this.crowi.model('Page');
  250. const { PageQueryBuilder } = Page;
  251. const Bookmark = this.crowi.model('Bookmark');
  252. const PageTagRelation = this.crowi.model('PageTagRelation');
  253. const searchEvent = this.searchEvent;
  254. // prepare functions invoked from custom streams
  255. const prepareBodyForCreate = this.prepareBodyForCreate.bind(this);
  256. const shouldIndexed = this.shouldIndexed.bind(this);
  257. const bulkWrite = this.client.bulk.bind(this.client);
  258. const findQuery = new PageQueryBuilder(queryFactory()).addConditionToExcludeRedirect().query;
  259. const countQuery = new PageQueryBuilder(queryFactory()).addConditionToExcludeRedirect().query;
  260. const totalCount = await countQuery.count();
  261. const readStream = findQuery
  262. // populate data which will be referenced by prepareBodyForCreate()
  263. .populate([
  264. { path: 'creator', model: 'User', select: 'username' },
  265. { path: 'revision', model: 'Revision', select: 'body' },
  266. ])
  267. .snapshot()
  268. .lean()
  269. .cursor();
  270. let skipped = 0;
  271. const thinOutStream = new Transform({
  272. objectMode: true,
  273. async transform(doc, encoding, callback) {
  274. if (shouldIndexed(doc)) {
  275. this.push(doc);
  276. }
  277. else {
  278. skipped++;
  279. }
  280. callback();
  281. },
  282. });
  283. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  284. const appendBookmarkCountStream = new Transform({
  285. objectMode: true,
  286. async transform(chunk, encoding, callback) {
  287. const pageIds = chunk.map(doc => doc._id);
  288. const idToCountMap = await Bookmark.getPageIdToCountMap(pageIds);
  289. const idsHavingCount = Object.keys(idToCountMap);
  290. // append count
  291. chunk
  292. .filter(doc => idsHavingCount.includes(doc._id.toString()))
  293. .forEach((doc) => {
  294. // append count from idToCountMap
  295. doc.bookmarkCount = idToCountMap[doc._id.toString()];
  296. });
  297. this.push(chunk);
  298. callback();
  299. },
  300. });
  301. const appendTagNamesStream = new Transform({
  302. objectMode: true,
  303. async transform(chunk, encoding, callback) {
  304. const pageIds = chunk.map(doc => doc._id);
  305. const idToTagNamesMap = await PageTagRelation.getIdToTagNamesMap(pageIds);
  306. const idsHavingTagNames = Object.keys(idToTagNamesMap);
  307. // append tagNames
  308. chunk
  309. .filter(doc => idsHavingTagNames.includes(doc._id.toString()))
  310. .forEach((doc) => {
  311. // append tagName from idToTagNamesMap
  312. doc.tagNames = idToTagNamesMap[doc._id.toString()];
  313. });
  314. this.push(chunk);
  315. callback();
  316. },
  317. });
  318. let count = 0;
  319. const writeStream = new Writable({
  320. objectMode: true,
  321. async write(batch, encoding, callback) {
  322. const body = [];
  323. batch.forEach(doc => prepareBodyForCreate(body, doc));
  324. try {
  325. const res = await bulkWrite({
  326. body,
  327. requestTimeout: Infinity,
  328. });
  329. count += (res.items || []).length;
  330. logger.info(`Adding pages progressing: (count=${count}, errors=${res.errors}, took=${res.took}ms)`);
  331. if (isEmittingProgressEvent) {
  332. searchEvent.emit('addPageProgress', totalCount, count, skipped);
  333. }
  334. }
  335. catch (err) {
  336. logger.error('addAllPages error on add anyway: ', err);
  337. }
  338. callback();
  339. },
  340. final(callback) {
  341. logger.info(`Adding pages has terminated: (totalCount=${totalCount}, skipped=${skipped})`);
  342. if (isEmittingProgressEvent) {
  343. searchEvent.emit('finishAddPage', totalCount, count, skipped);
  344. }
  345. callback();
  346. },
  347. });
  348. readStream
  349. .pipe(thinOutStream)
  350. .pipe(batchStream)
  351. .pipe(appendBookmarkCountStream)
  352. .pipe(appendTagNamesStream)
  353. .pipe(writeStream);
  354. return streamToPromise(writeStream);
  355. };
  356. SearchClient.prototype.deletePages = function(pages) {
  357. const self = this;
  358. const body = [];
  359. pages.map((page) => {
  360. self.prepareBodyForDelete(body, page);
  361. return;
  362. });
  363. logger.debug('deletePages(): Sending Request to ES', body);
  364. return this.client.bulk({
  365. body,
  366. });
  367. };
  368. /**
  369. * search returning type:
  370. * {
  371. * meta: { total: Integer, results: Integer},
  372. * data: [ pages ...],
  373. * }
  374. */
  375. SearchClient.prototype.search = async function(query) {
  376. // for debug
  377. if (process.env.NODE_ENV === 'development') {
  378. const result = await this.client.indices.validateQuery({
  379. explain: true,
  380. body: {
  381. query: query.body.query,
  382. },
  383. });
  384. logger.debug('ES returns explanations: ', result.explanations);
  385. }
  386. const result = await this.client.search(query);
  387. // for debug
  388. logger.debug('ES result: ', result);
  389. return {
  390. meta: {
  391. took: result.took,
  392. total: result.hits.total,
  393. results: result.hits.hits.length,
  394. },
  395. data: result.hits.hits.map((elm) => {
  396. return { _id: elm._id, _score: elm._score, _source: elm._source };
  397. }),
  398. };
  399. };
  400. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option) {
  401. // getting path by default is almost for debug
  402. let fields = ['path', 'bookmark_count', 'tag_names'];
  403. if (option) {
  404. fields = option.fields || fields;
  405. }
  406. // default is only id field, sorted by updated_at
  407. const query = {
  408. index: this.aliasName,
  409. type: 'pages',
  410. body: {
  411. sort: [{ updated_at: { order: 'desc' } }],
  412. query: {}, // query
  413. _source: fields,
  414. },
  415. };
  416. this.appendResultSize(query);
  417. return query;
  418. };
  419. SearchClient.prototype.createSearchQuerySortedByScore = function(option) {
  420. let fields = ['path', 'bookmark_count', 'tag_names'];
  421. if (option) {
  422. fields = option.fields || fields;
  423. }
  424. // sort by score
  425. const query = {
  426. index: this.aliasName,
  427. type: 'pages',
  428. body: {
  429. sort: [{ _score: { order: 'desc' } }],
  430. query: {}, // query
  431. _source: fields,
  432. },
  433. };
  434. this.appendResultSize(query);
  435. return query;
  436. };
  437. SearchClient.prototype.appendResultSize = function(query, from, size) {
  438. query.from = from || this.DEFAULT_OFFSET;
  439. query.size = size || this.DEFAULT_LIMIT;
  440. };
  441. SearchClient.prototype.initializeBoolQuery = function(query) {
  442. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  443. if (!query.body.query.bool) {
  444. query.body.query.bool = {};
  445. }
  446. const isInitialized = (query) => { return !!query && Array.isArray(query) };
  447. if (!isInitialized(query.body.query.bool.filter)) {
  448. query.body.query.bool.filter = [];
  449. }
  450. if (!isInitialized(query.body.query.bool.must)) {
  451. query.body.query.bool.must = [];
  452. }
  453. if (!isInitialized(query.body.query.bool.must_not)) {
  454. query.body.query.bool.must_not = [];
  455. }
  456. return query;
  457. };
  458. SearchClient.prototype.appendCriteriaForQueryString = function(query, queryString) {
  459. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  460. // parse
  461. const parsedKeywords = this.parseQueryString(queryString);
  462. if (parsedKeywords.match.length > 0) {
  463. const q = {
  464. multi_match: {
  465. query: parsedKeywords.match.join(' '),
  466. type: 'most_fields',
  467. fields: ['path.ja^2', 'path.en^2', 'body.ja', 'body.en'],
  468. },
  469. };
  470. query.body.query.bool.must.push(q);
  471. }
  472. if (parsedKeywords.not_match.length > 0) {
  473. const q = {
  474. multi_match: {
  475. query: parsedKeywords.not_match.join(' '),
  476. fields: ['path.ja', 'path.en', 'body.ja', 'body.en'],
  477. operator: 'or',
  478. },
  479. };
  480. query.body.query.bool.must_not.push(q);
  481. }
  482. if (parsedKeywords.phrase.length > 0) {
  483. const phraseQueries = [];
  484. parsedKeywords.phrase.forEach((phrase) => {
  485. phraseQueries.push({
  486. multi_match: {
  487. query: phrase, // each phrase is quoteted words
  488. type: 'phrase',
  489. fields: [
  490. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  491. 'path.raw^2',
  492. 'body',
  493. ],
  494. },
  495. });
  496. });
  497. query.body.query.bool.must.push(phraseQueries);
  498. }
  499. if (parsedKeywords.not_phrase.length > 0) {
  500. const notPhraseQueries = [];
  501. parsedKeywords.not_phrase.forEach((phrase) => {
  502. notPhraseQueries.push({
  503. multi_match: {
  504. query: phrase, // each phrase is quoteted words
  505. type: 'phrase',
  506. fields: [
  507. // Not use "*.ja" fields here, because we want to analyze (parse) search words
  508. 'path.raw^2',
  509. 'body',
  510. ],
  511. },
  512. });
  513. });
  514. query.body.query.bool.must_not.push(notPhraseQueries);
  515. }
  516. if (parsedKeywords.prefix.length > 0) {
  517. const queries = parsedKeywords.prefix.map((path) => {
  518. return { prefix: { 'path.raw': path } };
  519. });
  520. query.body.query.bool.filter.push({ bool: { should: queries } });
  521. }
  522. if (parsedKeywords.not_prefix.length > 0) {
  523. const queries = parsedKeywords.not_prefix.map((path) => {
  524. return { prefix: { 'path.raw': path } };
  525. });
  526. query.body.query.bool.filter.push({ bool: { must_not: queries } });
  527. }
  528. if (parsedKeywords.tag.length > 0) {
  529. const queries = parsedKeywords.tag.map((tag) => {
  530. return { term: { tag_names: tag } };
  531. });
  532. query.body.query.bool.filter.push({ bool: { must: queries } });
  533. }
  534. if (parsedKeywords.not_tag.length > 0) {
  535. const queries = parsedKeywords.not_tag.map((tag) => {
  536. return { term: { tag_names: tag } };
  537. });
  538. query.body.query.bool.filter.push({ bool: { must_not: queries } });
  539. }
  540. };
  541. SearchClient.prototype.filterPagesByViewer = async function(query, user, userGroups) {
  542. const showPagesRestrictedByOwner = !this.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  543. const showPagesRestrictedByGroup = !this.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  544. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  545. const Page = this.crowi.model('Page');
  546. const {
  547. GRANT_PUBLIC, GRANT_RESTRICTED, GRANT_SPECIFIED, GRANT_OWNER, GRANT_USER_GROUP,
  548. } = Page;
  549. const grantConditions = [
  550. { term: { grant: GRANT_PUBLIC } },
  551. ];
  552. // ensure to hit to GRANT_RESTRICTED pages that the user specified at own
  553. if (user != null) {
  554. grantConditions.push(
  555. {
  556. bool: {
  557. must: [
  558. { term: { grant: GRANT_RESTRICTED } },
  559. { term: { granted_users: user._id.toString() } },
  560. ],
  561. },
  562. },
  563. );
  564. }
  565. if (showPagesRestrictedByOwner) {
  566. grantConditions.push(
  567. { term: { grant: GRANT_SPECIFIED } },
  568. { term: { grant: GRANT_OWNER } },
  569. );
  570. }
  571. else if (user != null) {
  572. grantConditions.push(
  573. {
  574. bool: {
  575. must: [
  576. { term: { grant: GRANT_SPECIFIED } },
  577. { term: { granted_users: user._id.toString() } },
  578. ],
  579. },
  580. },
  581. {
  582. bool: {
  583. must: [
  584. { term: { grant: GRANT_OWNER } },
  585. { term: { granted_users: user._id.toString() } },
  586. ],
  587. },
  588. },
  589. );
  590. }
  591. if (showPagesRestrictedByGroup) {
  592. grantConditions.push(
  593. { term: { grant: GRANT_USER_GROUP } },
  594. );
  595. }
  596. else if (userGroups != null && userGroups.length > 0) {
  597. const userGroupIds = userGroups.map((group) => { return group._id.toString() });
  598. grantConditions.push(
  599. {
  600. bool: {
  601. must: [
  602. { term: { grant: GRANT_USER_GROUP } },
  603. { terms: { granted_group: userGroupIds } },
  604. ],
  605. },
  606. },
  607. );
  608. }
  609. query.body.query.bool.filter.push({ bool: { should: grantConditions } });
  610. };
  611. SearchClient.prototype.filterPortalPages = function(query) {
  612. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  613. query.body.query.bool.must_not.push(this.queries.USER);
  614. query.body.query.bool.filter.push(this.queries.PORTAL);
  615. };
  616. SearchClient.prototype.filterPublicPages = function(query) {
  617. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  618. query.body.query.bool.must_not.push(this.queries.USER);
  619. query.body.query.bool.filter.push(this.queries.PUBLIC);
  620. };
  621. SearchClient.prototype.filterUserPages = function(query) {
  622. query = this.initializeBoolQuery(query); // eslint-disable-line no-param-reassign
  623. query.body.query.bool.filter.push(this.queries.USER);
  624. };
  625. SearchClient.prototype.filterPagesByType = function(query, type) {
  626. const Page = this.crowi.model('Page');
  627. switch (type) {
  628. case Page.TYPE_PORTAL:
  629. return this.filterPortalPages(query);
  630. case Page.TYPE_PUBLIC:
  631. return this.filterPublicPages(query);
  632. case Page.TYPE_USER:
  633. return this.filterUserPages(query);
  634. default:
  635. return query;
  636. }
  637. };
  638. SearchClient.prototype.appendFunctionScore = function(query, queryString) {
  639. const User = this.crowi.model('User');
  640. const count = User.count({}) || 1;
  641. const minScore = queryString.length * 0.1 - 1; // increase with length
  642. logger.debug('min_score: ', minScore);
  643. query.body.query = {
  644. function_score: {
  645. query: { ...query.body.query },
  646. // // disable min_score -- 2019.02.28 Yuki Takei
  647. // // more precise adjustment is needed...
  648. // min_score: minScore,
  649. field_value_factor: {
  650. field: 'bookmark_count',
  651. modifier: 'log1p',
  652. factor: 10000 / count,
  653. missing: 0,
  654. },
  655. boost_mode: 'sum',
  656. },
  657. };
  658. };
  659. SearchClient.prototype.searchKeyword = async function(queryString, user, userGroups, option) {
  660. const from = option.offset || null;
  661. const size = option.limit || null;
  662. const type = option.type || null;
  663. const query = this.createSearchQuerySortedByScore();
  664. this.appendCriteriaForQueryString(query, queryString);
  665. this.filterPagesByType(query, type);
  666. await this.filterPagesByViewer(query, user, userGroups);
  667. this.appendResultSize(query, from, size);
  668. this.appendFunctionScore(query, queryString);
  669. return this.search(query);
  670. };
  671. SearchClient.prototype.parseQueryString = function(queryString) {
  672. const matchWords = [];
  673. const notMatchWords = [];
  674. const phraseWords = [];
  675. const notPhraseWords = [];
  676. const prefixPaths = [];
  677. const notPrefixPaths = [];
  678. const tags = [];
  679. const notTags = [];
  680. queryString.trim();
  681. queryString = queryString.replace(/\s+/g, ' '); // eslint-disable-line no-param-reassign
  682. // First: Parse phrase keywords
  683. const phraseRegExp = new RegExp(/(-?"[^"]+")/g);
  684. const phrases = queryString.match(phraseRegExp);
  685. if (phrases !== null) {
  686. queryString = queryString.replace(phraseRegExp, ''); // eslint-disable-line no-param-reassign
  687. phrases.forEach((phrase) => {
  688. phrase.trim();
  689. if (phrase.match(/^-/)) {
  690. notPhraseWords.push(phrase.replace(/^-/, ''));
  691. }
  692. else {
  693. phraseWords.push(phrase);
  694. }
  695. });
  696. }
  697. // Second: Parse other keywords (include minus keywords)
  698. queryString.split(' ').forEach((word) => {
  699. if (word === '') {
  700. return;
  701. }
  702. // https://regex101.com/r/pN9XfK/1
  703. const matchNegative = word.match(/^-(prefix:|tag:)?(.+)$/);
  704. // https://regex101.com/r/3qw9FQ/1
  705. const matchPositive = word.match(/^(prefix:|tag:)?(.+)$/);
  706. if (matchNegative != null) {
  707. if (matchNegative[1] === 'prefix:') {
  708. notPrefixPaths.push(matchNegative[2]);
  709. }
  710. else if (matchNegative[1] === 'tag:') {
  711. notTags.push(matchNegative[2]);
  712. }
  713. else {
  714. notMatchWords.push(matchNegative[2]);
  715. }
  716. }
  717. else if (matchPositive != null) {
  718. if (matchPositive[1] === 'prefix:') {
  719. prefixPaths.push(matchPositive[2]);
  720. }
  721. else if (matchPositive[1] === 'tag:') {
  722. tags.push(matchPositive[2]);
  723. }
  724. else {
  725. matchWords.push(matchPositive[2]);
  726. }
  727. }
  728. });
  729. return {
  730. match: matchWords,
  731. not_match: notMatchWords,
  732. phrase: phraseWords,
  733. not_phrase: notPhraseWords,
  734. prefix: prefixPaths,
  735. not_prefix: notPrefixPaths,
  736. tag: tags,
  737. not_tag: notTags,
  738. };
  739. };
  740. SearchClient.prototype.syncPageUpdated = async function(page, user) {
  741. logger.debug('SearchClient.syncPageUpdated', page.path);
  742. // delete if page should not indexed
  743. if (!this.shouldIndexed(page)) {
  744. try {
  745. await this.deletePages([page]);
  746. }
  747. catch (err) {
  748. logger.error('deletePages:ES Error', err);
  749. }
  750. return;
  751. }
  752. return this.updateOrInsertPageById(page._id);
  753. };
  754. SearchClient.prototype.syncPageDeleted = async function(page, user) {
  755. debug('SearchClient.syncPageDeleted', page.path);
  756. try {
  757. return await this.deletePages([page]);
  758. }
  759. catch (err) {
  760. logger.error('deletePages:ES Error', err);
  761. }
  762. };
  763. SearchClient.prototype.syncBookmarkChanged = async function(pageId) {
  764. logger.debug('SearchClient.syncBookmarkChanged', pageId);
  765. return this.updateOrInsertPageById(pageId);
  766. };
  767. SearchClient.prototype.syncTagChanged = async function(page) {
  768. logger.debug('SearchClient.syncTagChanged', page.path);
  769. return this.updateOrInsertPageById(page._id);
  770. };
  771. module.exports = SearchClient;