Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 | 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 16x 16x 3x 3x 3x 3x 3x 3x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x | import path from 'path' import elasticsearch from 'elasticsearch' import Debug from 'debug' import moment from 'moment' import fs from 'fs' const debug = Debug('crowi:lib:search') // TODO: replace to class function SearchClient(this: any, crowi, esUri) { this.DEFAULT_OFFSET = 0 this.DEFAULT_LIMIT = 50 this.esNodeName = '-' this.esNodeNames = [] this.esVersion = 'unknown' this.esVersions = [] this.esPlugin = [] this.esPlugins = [] this.esUri = esUri this.crowi = crowi this.searchEvent = crowi.event('Search') // In Elasticsearch RegExp, we don't need to used ^ and $. // Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/query-dsl-regexp-query.html#_standard_operators this.queries = { PORTAL: { regexp: { 'path.raw': '.*/', }, }, PUBLIC: { regexp: { 'path.raw': '.*[^/]', }, }, USER: { prefix: { 'path.raw': '/user/', }, }, } const uri = this.parseUri(this.esUri) this.host = uri.host this.indexNames = { base: uri.indexName, current: `${uri.indexName}-current`, } this.client = new elasticsearch.Client({ host: this.host, requestTimeout: 5000, // log: 'debug', }) this.registerUpdateEvent() } SearchClient.prototype.requireMappingFile = function() { const { resourceDir } = this.crowi let fileName = path.join(resourceDir + 'search/mappings.json') if ('analysis-kuromoji' in this.esPlugins) { fileName = path.join(resourceDir + 'search/mappings-kuromoji.json') } if ('analysis-sudachi' in this.esPlugins) { fileName = path.join(resourceDir + 'search/mappings-sudachi.json') } return JSON.parse(fs.readFileSync(fileName).toString()) } SearchClient.prototype.checkESVersion = async function() { try { const nodes = await this.client.nodes.info() if (!nodes._nodes || !nodes.nodes) { throw new Error('no nodes info') } for (const [nodeName, nodeInfo] of Object.entries<any>(nodes.nodes)) { this.esNodeName = nodeName this.esNodeNames.push(nodeName) this.esVersion = nodeInfo.version this.esVersions.push(nodeInfo.version) this.esPlugin = nodeInfo.plugins this.esPlugins.push(nodeInfo.plugins) } } catch (error) { debug('es check version error:', error) } } SearchClient.prototype.registerUpdateEvent = function() { const pageEvent = this.crowi.event('Page') pageEvent.on('create', this.syncPageCreated.bind(this)) pageEvent.on('update', this.syncPageUpdated.bind(this)) pageEvent.on('delete', this.syncPageDeleted.bind(this)) const bookmarkEvent = this.crowi.event('Bookmark') bookmarkEvent.on('create', this.syncBookmarkChanged.bind(this)) bookmarkEvent.on('delete', this.syncBookmarkChanged.bind(this)) } SearchClient.prototype.shouldIndexed = function(page) { if (page.redirectTo !== null) { return false } // FIXME: use STATUS_DELETED // isDeleted() couldn't use here because of lean() if (page.status === 'deleted') { return false } return true } // BONSAI_URL is following format: // => https://{ID}:{PASSWORD}@{HOST} SearchClient.prototype.parseUri = function(uri) { let indexName = 'crowi' let host = uri let m Eif ((m = uri.match(/^(https?:\/\/[^/]+)\/(.+)$/))) { host = m[1] indexName = m[2] } return { host, indexName, } } SearchClient.prototype.createIndexName = function() { const datetime = moment().format('YYYYMMDDHHmmss') return `${this.indexNames.base}-${datetime}` } SearchClient.prototype.createIndex = async function(index) { await this.checkESVersion() const body = this.requireMappingFile() return this.client.indices.create({ index, body }) } /** * Search operation: always access to `{indexName}-current` * * Build index (for the first time): * 1. Creating index with current timestamp: ex: {indexName}-20190625230435 * 2. Add all pages to created index. * 3. Add alias to created index. alias {indexName}-current` to {index-name}-20190625230435 * * Rebuild index: * 1. Creating index with current timestamp: * ex. * {indexName}-20190505220000 <-- existing index (current {indexName}-current) * {indexName}-20190625230000 <-- created index. * 2. Add all pages to created index. * 3. Add alias to created index. And remove alias from old existing index. * ex. * {indexName}-20190505220000 <-- remove alias * {indexName}-20190625230000 <-- `{indexName}-current` * 4. Delete old existing index. ({indexName}-20190505220000) * */ SearchClient.prototype.buildIndex = async function() { const newIndexName = this.createIndexName() try { // creating index anyway. await this.createIndex(newIndexName) debug('Index created.') } catch (err) { debug('Error (while creating new index)', newIndexName, err) throw new Error('Error while creating index.') } try { await this.addAllPages(newIndexName) debug('Added all pages.') } catch (err) { debug('Error (while adding all pages)', err) throw new Error('Error while adding all pages.') } // remove `current` alias from old existing index, and add `current` to newIndexName index. const alias = await this.getAlias() const add = { index: newIndexName, alias: this.indexNames.current, } if (alias) { const remove = { index: alias.index, alias: alias.alias, } await this.updateAliases({ add, remove }) } else { await this.updateAliases({ add }) } const indices = await this.getIndices() const deleteIndices = indices.filter(index => index !== newIndexName) // for the first time, no old indices exists if (deleteIndices.length === 0) { return } await this.deleteIndices(deleteIndices) } SearchClient.prototype.getIndices = async function() { const indices = await this.client.cat.indices({ format: 'json' }) return indices.map(({ index }) => index).filter(index => index.startsWith(this.indexNames.base)) } SearchClient.prototype.deleteIndices = function(indices) { return this.client.indices.delete({ index: indices }) } SearchClient.prototype.existsAlias = function() { return this.client.indices.existsAlias({ name: this.indexNames.current }) } SearchClient.prototype.getAlias = function() { const existsAlias = this.existsAlias() if (existsAlias) { const aliases = this.client.cat.aliases({ name: this.indexNames.current, format: 'json' }) if (aliases.length > 0) { return aliases[0] } } return null } SearchClient.prototype.putAlias = async function(index) { return this.client.indices.putAlias({ index, name: this.indexNames.current }) } SearchClient.prototype.ensureAlias = async function() { const exists = await this.existsAlias() if (!exists) { const indices = await this.getIndices() if (indices.length > 0) { await this.putAlias(indices[0]) return true } } return exists } SearchClient.prototype.updateAliases = async function(actions) { return this.client.indices.updateAliases({ body: { actions } }) } SearchClient.prototype.prepareBodyForUpdate = function(body, page, index = null) { if (!Array.isArray(body)) { throw new Error('Body must be an array.') } const command = { update: { _index: index || this.indexNames.current, _type: 'pages', _id: page._id.toString(), }, } const document = { doc: { path: page.path, body: page.revision.body, grant: page.grant, comment_count: page.commentCount, bookmark_count: page.bookmarkCount || 0, like_count: page.liker.length || 0, updated_at: page.updatedAt, }, doc_as_upsert: true, } body.push(command) body.push(document) } SearchClient.prototype.prepareBodyForCreate = function(body, page, index = null) { if (!Array.isArray(body)) { throw new Error('Body must be an array.') } const command = { index: { _index: index || this.indexNames.current, _type: 'pages', _id: page._id.toString(), }, } const bookmarkCount = page.bookmarkCount || 0 const document = { path: page.path, body: page.revision.body, username: page.creator.username, grant: page.grant, comment_count: page.commentCount, bookmark_count: bookmarkCount, like_count: page.liker.length || 0, created_at: page.createdAt, updated_at: page.updatedAt, } body.push(command) body.push(document) } SearchClient.prototype.prepareBodyForDelete = function(body, page, index = null) { if (!Array.isArray(body)) { throw new Error('Body must be an array.') } const command = { delete: { _index: index || this.indexNames.current, _type: 'pages', _id: page._id.toString(), }, } body.push(command) } SearchClient.prototype.addPages = async function(pages) { const Bookmark = this.crowi.model('Bookmark') const body = [] for (const page of pages) { page.bookmarkCount = await Bookmark.countByPageId(page._id) this.prepareBodyForCreate(body, page) } debug('addPages(): Sending Request to ES', body) return this.client.bulk({ body: body, }) } SearchClient.prototype.updatePages = function(pages) { const body = [] pages.map(page => { this.prepareBodyForUpdate(body, page) }) debug('updatePages(): Sending Request to ES', body) return this.client.bulk({ body: body, }) } SearchClient.prototype.deletePages = function(pages) { const body = [] pages.map(page => { this.prepareBodyForDelete(body, page) }) debug('deletePages(): Sending Request to ES', body) return this.client.bulk({ body: body, }) } SearchClient.prototype.addAllPages = async function(index) { const Page = this.crowi.model('Page') const allPageCount = await Page.allPageCount() const Bookmark = this.crowi.model('Bookmark') const cursor = Page.getStreamOfFindAll({ publicOnly: false }) let body = [] let sent = 0 let skipped = 0 let total = 0 return new Promise((resolve, reject) => { const bulkSend = body => { this.client .bulk({ body: body, requestTimeout: Infinity, }) .then(res => { debug('addAllPages add anyway (items, errors, took): ', (res.items || []).length, res.errors, res.took, 'ms') }) .catch(err => { debug('addAllPages error on add anyway: ', err) }) } cursor .eachAsync(async doc => { if (!doc.creator || !doc.revision || !this.shouldIndexed(doc)) { // debug('Skipped', doc.path); skipped++ return } total++ const bookmarkCount = await Bookmark.countByPageId(doc._id) const page = { ...doc, bookmarkCount } this.prepareBodyForCreate(body, page, index) if (body.length >= 4000) { // send each 2000 docs. (body has 2 elements for each data) sent++ debug('Sending request (seq, total, skipped)', sent, total, skipped) bulkSend(body) this.searchEvent.emit('addPageProgress', allPageCount, total, skipped) body = [] } }) .then(() => { // send all remaining data on body[] debug('Sending last body of bulk operation:', body.length) bulkSend(body) this.searchEvent.emit('finishAddPage', allPageCount, total, skipped) resolve() }) .catch(e => { debug('Error wile iterating cursor.eacnAsync()', e) reject(e) }) }) } /** * search returning type: * { * meta: { total: Integer, results: Integer}, * data: [ pages ...], * } */ SearchClient.prototype.search = function(query) { return new Promise((resolve, reject) => { this.client .search(query) .then(function(data) { const result = { meta: { took: data.took, total: data.hits.total, results: data.hits.hits.length, }, data: data.hits.hits.map(function(elm) { return { _id: elm._id, _score: elm._score, _source: elm._source } }), } resolve(result) }) .catch(function(err) { debug('Search error', err) reject(err) }) }) } SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option) { // getting path by default is almost for debug let fields = ['path', 'bookmark_count'] if (option) { fields = option.fields || fields } // default is only id field, sorted by updated_at const query = { index: this.indexNames.current, type: 'pages', body: { sort: [{ updated_at: { order: 'desc' } }], query: {}, // query _source: fields, }, } this.appendResultSize(query) return query } SearchClient.prototype.createSearchQuerySortedByScore = function(option) { let fields = ['path', 'bookmark_count'] if (option) { fields = option.fields || fields } // sort by score const query = { index: this.indexNames.current, type: 'pages', body: { sort: [{ _score: { order: 'desc' } }], query: {}, // query _source: fields, }, } this.appendResultSize(query) return query } SearchClient.prototype.appendResultSize = function(query, from, size) { query.from = from || this.DEFAULT_OFFSET query.size = size || this.DEFAULT_LIMIT } SearchClient.prototype.initializeBoolQuery = function(query) { // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt() if (!query.body.query.bool) { query.body.query.bool = {} } const isInitialized = query => !!query && Array.isArray(query) if (!isInitialized(query.body.query.bool.filter)) { query.body.query.bool.filter = [] } if (!isInitialized(query.body.query.bool.must)) { query.body.query.bool.must = [] } if (!isInitialized(query.body.query.bool.must_not)) { query.body.query.bool.must_not = [] } return query } SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword) { query = this.initializeBoolQuery(query) const appendMultiMatchQuery = function(query, type, keywords) { let target let operator = 'and' switch (type) { case 'not_match': target = query.body.query.bool.must_not operator = 'or' break case 'match': default: target = query.body.query.bool.must } target.push({ multi_match: { query: keywords.join(' '), // TODO: By user's i18n setting, change boost or search target fields fields: ['path.ja^2', 'body.ja', 'path.en^1.2', 'body.en'], operator: operator, }, }) return query } const parsedKeywords = this.getParsedKeywords(keyword) if (parsedKeywords.match.length > 0) { query = appendMultiMatchQuery(query, 'match', parsedKeywords.match) } if (parsedKeywords.not_match.length > 0) { query = appendMultiMatchQuery(query, 'not_match', parsedKeywords.not_match) } if (parsedKeywords.phrase.length > 0) { const phraseQueries: any = [] parsedKeywords.phrase.forEach(function(phrase) { phraseQueries.push({ multi_match: { query: phrase, // each phrase is quoteted words type: 'phrase', fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words 'path.raw^2', 'body', ], }, }) }) query.body.query.bool.must.push(phraseQueries) } if (parsedKeywords.not_phrase.length > 0) { const notPhraseQueries: any = [] parsedKeywords.not_phrase.forEach(function(phrase) { notPhraseQueries.push({ multi_match: { query: phrase, // each phrase is quoteted words type: 'phrase', fields: [ // Not use "*.ja" fields here, because we want to analyze (parse) search words 'path.raw^2', 'body', ], }, }) }) query.body.query.bool.must_not.push(notPhraseQueries) } } SearchClient.prototype.appendCriteriaForPathFilter = function(query, path) { query = this.initializeBoolQuery(query) if (path.match(/\/$/)) { path = path.substr(0, path.length - 1) } query.body.query.bool.filter.push({ wildcard: { 'path.raw': path + '/*', }, }) } SearchClient.prototype.filterPortalPages = function(query) { query = this.initializeBoolQuery(query) query.body.query.bool.must_not.push(this.queries.USER) query.body.query.bool.filter.push(this.queries.PORTAL) } SearchClient.prototype.filterPublicPages = function(query) { query = this.initializeBoolQuery(query) query.body.query.bool.must_not.push(this.queries.USER) query.body.query.bool.filter.push(this.queries.PUBLIC) } SearchClient.prototype.filterUserPages = function(query) { query = this.initializeBoolQuery(query) query.body.query.bool.filter.push(this.queries.USER) } SearchClient.prototype.filterPagesByType = function(query, type) { const Page = this.crowi.model('Page') switch (type) { case Page.TYPE_PORTAL: return this.filterPortalPages(query) case Page.TYPE_PUBLIC: return this.filterPublicPages(query) case Page.TYPE_USER: return this.filterUserPages(query) default: return query } } SearchClient.prototype.filterPagesByUser = function(query, user) { const Page = this.crowi.model('Page') query = this.initializeBoolQuery(query) query.body.query.bool.must_not.push({ bool: { must_not: { match: { username: user.username } }, should: [{ match: { grant: Page.GRANT_RESTRICTED } }, { match: { grant: Page.GRANT_SPECIFIED } }, { match: { grant: Page.GRANT_OWNER } }], }, }) } SearchClient.prototype.appendFunctionScore = function(query) { const User = this.crowi.model('User') const count = User.countDocuments({}) || 1 // newScore = oldScore + log(1 + factor * 'bookmark_count') query.body.query = { function_score: { query: { ...query.body.query }, field_value_factor: { field: 'bookmark_count', modifier: 'log1p', factor: 10000 / count, missing: 0, }, boost_mode: 'sum', }, } } SearchClient.prototype.searchKeyword = function(keyword, user = {}, option = {}) { const from = option.offset || null const size = option.limit || null const type = option.type || null const query = this.createSearchQuerySortedByScore() this.appendCriteriaForKeywordContains(query, keyword) this.filterPagesByType(query, type) this.filterPagesByUser(query, user) this.appendResultSize(query, from, size) this.appendFunctionScore(query) const bool = query.body.query.function_score.query.bool debug('searching ...', keyword, type) debug('filter', bool.filter) debug('must', bool.must) debug('must_not', bool.must_not) return this.search(query) } SearchClient.prototype.searchByPath = function(keyword, prefix) { // TODO path 名だけから検索 } SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, user = {}, option = {}) { const from = option.offset || null const size = option.limit || null const type = option.type || null const query = this.createSearchQuerySortedByScore() this.appendCriteriaForKeywordContains(query, keyword) this.appendCriteriaForPathFilter(query, path) this.filterPagesByType(query, type) this.filterPagesByUser(query, user) this.appendResultSize(query, from, size) this.appendFunctionScore(query) return this.search(query) } SearchClient.prototype.getParsedKeywords = function(keyword) { const matchWords: any = [] const notMatchWords: any = [] const phraseWords: any = [] const notPhraseWords: any = [] keyword.trim() keyword = keyword.replace(/\s+/g, ' ') // First: Parse phrase keywords const phraseRegExp = new RegExp(/(-?"[^"]+")/g) const phrases = keyword.match(phraseRegExp) if (phrases !== null) { keyword = keyword.replace(phraseRegExp, '') phrases.forEach(function(phrase) { phrase.trim() if (phrase.match(/^-/)) { notPhraseWords.push(phrase.replace(/^-/, '')) } else { phraseWords.push(phrase) } }) } // Second: Parse other keywords (include minus keywords) keyword.split(' ').forEach(function(word) { if (word === '') { return } if (word.match(/^-(.+)$/)) { notMatchWords.push(RegExp.$1) } else { matchWords.push(word) } }) return { match: matchWords, not_match: notMatchWords, phrase: phraseWords, not_phrase: notPhraseWords, } } SearchClient.prototype.syncPageCreated = function(page, user, bookmarkCount = 0) { debug('SearchClient.syncPageCreated', page.path) if (!this.shouldIndexed(page)) { return } page.bookmarkCount = bookmarkCount this.addPages([page]) .then(function(res) { debug('ES Response', res) }) .catch(function(err) { debug('ES Error', err) }) } SearchClient.prototype.syncPageUpdated = function(page, user, bookmarkCount = 0) { debug('SearchClient.syncPageUpdated', page.path) debug('Page:', page) // TODO delete if (!this.shouldIndexed(page)) { this.deletePages([page]) .then(function(res) { debug('deletePages: ES Response', res) }) .catch(function(err) { debug('deletePages:ES Error', err) }) return } page.bookmarkCount = bookmarkCount this.updatePages([page]) .then(function(res) { debug('ES Response', res) }) .catch(function(err) { debug('ES Error', err) }) } SearchClient.prototype.syncPageDeleted = function(page, user) { debug('SearchClient.syncPageDeleted', page.path) this.deletePages([page]) .then(function(res) { debug('deletePages: ES Response', res) }) .catch(function(err) { debug('deletePages:ES Error', err) }) } SearchClient.prototype.syncBookmarkChanged = async function(pageId) { const Page = this.crowi.model('Page') const Bookmark = this.crowi.model('Bookmark') const [page, bookmarkCount] = await Promise.all([Page.findPageById(pageId), Bookmark.countByPageId(pageId)]) page.bookmarkCount = bookmarkCount this.updatePages([page]) .then(res => debug('ES Response', res)) .catch(err => debug('ES Error', err)) } export default SearchClient |