-
Notifications
You must be signed in to change notification settings - Fork 89
Search #231
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Search #231
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
79592f0
search implementation
talyguryn 794067c
add blur
talyguryn bab89c9
update z-index
talyguryn cb87739
enable search for cyrillic letters
talyguryn 03370dd
add short body
talyguryn 0cb6954
update logic
talyguryn 9fa3c90
Merge branch 'main' into feature/backend-search
talyguryn 80e9504
Update search.ts
talyguryn e237f27
Update search.ts
talyguryn 6db7fc8
Update search.ts
talyguryn e15a5e8
update
talyguryn a5d6f17
Update search.ts
talyguryn a9dd65c
add cache
talyguryn 488d825
add comments
talyguryn f355596
Merge branch 'main' into feature/backend-search
talyguryn ce4522d
Merge branch 'main' into feature/backend-search
talyguryn 5d004ac
Merge branch 'main' into feature/backend-search
talyguryn 86d26ba
Merge branch 'main' into feature/backend-search
talyguryn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,5 +8,5 @@ | |
| "watch": [ | ||
| "**/*" | ||
| ], | ||
| "ext": "js,twig" | ||
| "ext": "ts,js,twig" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
302 changes: 302 additions & 0 deletions
src/backend/controllers/search.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,302 @@ | ||
| import PageData from '../models/page.js'; | ||
| import Pages from '../controllers/pages.js'; | ||
| import urlify from '../utils/urlify.js'; | ||
| import Page from '../models/page.js'; | ||
|
|
||
| let globalWords: { [key: string]: {[key: string]: number} } = Object.create(null); | ||
| let globalPages: PageData[] = []; | ||
|
|
||
| class Search { | ||
| /** | ||
| * Initialize search | ||
| */ | ||
| public async init() { | ||
| if (globalWords && Object.keys(globalWords).length) { | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| await this.syncDB(); | ||
| } | ||
|
|
||
| /** | ||
| * Load all pages from DB and update globalWords | ||
| * Use this method when any page was updated | ||
| */ | ||
| public async syncDB() { | ||
| globalWords = Object.create(null); | ||
| globalPages = await this.getPages(); | ||
|
|
||
| /** | ||
| * Process all pages | ||
| */ | ||
| for await (const page of globalPages) { | ||
| /** | ||
| * Read content blocks from page | ||
| */ | ||
| for await (const block of page.body.blocks) { | ||
| const blockRatio = this.getBlockRatio(block); | ||
| const blockContent = this.getCleanTextFromBlock(block); | ||
| const blockWords: string[] = this.splitTextToWords(blockContent); | ||
|
|
||
| /** | ||
| * Process list of words in a block | ||
| */ | ||
| for await (const word of blockWords) { | ||
| if (!globalWords[word]) { | ||
| globalWords[word] = Object.create(null); | ||
| } | ||
|
|
||
| if (page._id) { | ||
| if (!globalWords[word][page._id]) { | ||
| globalWords[word][page._id] = 0; | ||
| } | ||
|
|
||
| /** | ||
| * Add page id to the list of pages with this word | ||
| */ | ||
| globalWords[word][page._id] += blockRatio; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| console.log('Done'); | ||
| } | ||
|
|
||
| /** | ||
| * Search for pages by given query | ||
| * @param searchString | ||
| */ | ||
| public async query(searchString: string) { | ||
| await this.init(); | ||
|
|
||
| const searchWords = this.splitTextToWords(searchString); | ||
|
|
||
| const goodPages = (await this.getPagesByWords(searchWords)) | ||
| .slice(0, 10); | ||
|
|
||
| const returnPages: {[key: string]: string|number, ratio: number}[] = []; | ||
|
|
||
| goodPages.forEach(({ pageId, ratio }) => { | ||
| const page = globalPages.filter(page => page._id === pageId).pop(); | ||
|
|
||
| if (!page) { | ||
| return; | ||
| } | ||
|
|
||
| let section = ''; | ||
|
|
||
| page.body.blocks.forEach((block: any) => { | ||
| let koef = 1; | ||
|
|
||
| let blockContent = this.getCleanTextFromBlock(block); | ||
|
|
||
| let shortBody = blockContent; | ||
|
|
||
| if (block.type === 'header') { | ||
| section = blockContent; | ||
| } | ||
|
|
||
| searchWords.forEach(word => { | ||
| if (blockContent.toLowerCase().indexOf(word) !== -1) { | ||
| koef *= 10; | ||
| } | ||
| }) | ||
|
|
||
| shortBody = this.highlightSubstring(shortBody, searchWords); | ||
|
|
||
| if (koef > 0) { | ||
| returnPages.push({ | ||
| ...page, | ||
| shortBody, | ||
| anchor: urlify(section), | ||
| section, | ||
| ratio: ratio * koef, | ||
| }) | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| return { | ||
| suggestions: ['description', 'about', 'contact'], | ||
| pages: returnPages | ||
| .sort((a, b) => b.ratio - a.ratio) | ||
| .slice(0, 15) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * | ||
| * @private | ||
| */ | ||
| private async getPages(): Promise<Page[]> { | ||
| return await Pages.getAll(); | ||
| } | ||
|
|
||
| /** | ||
| * Return list of pages with a given words | ||
| * @param words | ||
| * @private | ||
| */ | ||
| private async getPagesByWords(words: string[]) { | ||
| const pagesList: {[key: string]: number} = {}; | ||
|
|
||
| /** | ||
| * Get list of words starting with a words from the search query | ||
| */ | ||
| const validWords = Object.keys(globalWords) | ||
| .filter(word => { | ||
| return !!words.filter(searchWord => word.indexOf(searchWord) !== -1).length | ||
| }); | ||
|
|
||
| /** | ||
| * For each word get list of pages with this word | ||
| */ | ||
| validWords.forEach(word => { | ||
| Object.keys(globalWords[word]) | ||
| .forEach(pageId => { | ||
| if (!pagesList[pageId]) { | ||
| pagesList[pageId] = 0; | ||
| } | ||
|
|
||
| pagesList[pageId] += globalWords[word][pageId] | ||
| }) | ||
| }) | ||
|
|
||
| /** | ||
| * Sort pages by frequency of given words | ||
| */ | ||
| const sortedPagesList = Object.keys(pagesList) | ||
| .map(pageId => { | ||
| return { | ||
| pageId, | ||
| ratio: pagesList[pageId] | ||
| } | ||
| }) | ||
| .sort((a, b) => b.ratio - a.ratio); | ||
|
|
||
| return sortedPagesList; | ||
| } | ||
|
|
||
| /** | ||
| * Get block's ratio. It is used to calculate the weight of the words in the block | ||
| * @param block | ||
| * @private | ||
| */ | ||
| private getBlockRatio(block: any) { | ||
| switch (block.type) { | ||
| case 'header': | ||
| if (block.data.level === 1) { | ||
| return 16; | ||
| } else { | ||
| return 2; | ||
| } | ||
|
|
||
| case 'paragraph': | ||
| return 1.1; | ||
|
|
||
| case 'list': | ||
| return 1; | ||
|
|
||
| default: | ||
| return 0; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Return clear text content from block without HTML tags and special characters | ||
| * @param block | ||
| * @private | ||
| */ | ||
| private getCleanTextFromBlock(block: any): string { | ||
| let blockContent = ''; | ||
|
|
||
| switch (block.type) { | ||
| case 'header': | ||
| blockContent = block.data.text; | ||
| break; | ||
|
|
||
| case 'paragraph': | ||
| blockContent = block.data.text | ||
| break; | ||
|
|
||
| case 'list': | ||
| blockContent = block.data.items.join(' '); | ||
| break; | ||
|
|
||
| default: | ||
| return blockContent; | ||
| } | ||
|
|
||
| blockContent = this.removeHTMLTags(blockContent); | ||
| blockContent = this.removeHTMLSpecialCharacters(blockContent); | ||
|
|
||
| return blockContent; | ||
| } | ||
|
|
||
| /** | ||
| * Remove HTML tags from string. Only content inside tags will be left | ||
| * @param text | ||
| * @private | ||
| */ | ||
| private removeHTMLTags(text: string) { | ||
| return text.replace(/<[^>]*>?/gm, ''); | ||
| } | ||
|
|
||
| /** | ||
| * Remove special characters from text. For example: & " < > | ||
| * @param text | ||
| * @private | ||
| */ | ||
| private removeHTMLSpecialCharacters(text: string) { | ||
| return text.replace(/&[^;]*;?/gm, ''); | ||
| } | ||
|
|
||
| /** | ||
| * Split text to words | ||
| * @param text | ||
| * @private | ||
| */ | ||
| private splitTextToWords(text: string): string[] { | ||
| return text | ||
| // lowercase all words | ||
| .toLowerCase() | ||
|
|
||
| // remove punctuation | ||
| .replace(/[.,;:]/gi, '') | ||
|
|
||
| // left only letters (+cyrillic) and numbers | ||
| .replace(/[^a-zа-я0-9]/gi, ' ') | ||
|
|
||
| // remove multiple spaces | ||
| .replace(/\s+/g, ' ') | ||
|
|
||
| // remove spaces at the beginning and at the end | ||
| .trim() | ||
|
|
||
| // split to words by spaces | ||
| .split(' ') | ||
|
|
||
| // ignore words shorter than 3 chars | ||
| .filter(word => word.length >= 3); | ||
| } | ||
|
|
||
| /** | ||
| * Highlight substring in string with a span wrapper | ||
| */ | ||
| private highlightSubstring(text: string, words: string|string[]) { | ||
| if (typeof words === 'string') { | ||
| words = [words]; | ||
| } | ||
|
|
||
| const wordRegExp = new RegExp(words.join('|'), "ig"); | ||
| const CLASS_STYLE = 'search-word'; | ||
|
|
||
| return text.replace(wordRegExp, `<span class="${CLASS_STYLE}">$&</span>`); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Export initialized instance | ||
| */ | ||
| export default new Search(); |
3 changes: 3 additions & 0 deletions
src/backend/routes/api/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,15 @@ | ||
| import express from 'express'; | ||
|
|
||
| import pagesAPI from './pages.js'; | ||
| import transportAPI from './transport.js'; | ||
| import linksAPI from './links.js'; | ||
| import searchAPI from './search.js'; | ||
|
|
||
| const router = express.Router(); | ||
|
|
||
| router.use('/', pagesAPI); | ||
| router.use('/', transportAPI); | ||
| router.use('/', linksAPI); | ||
| router.use('/', searchAPI); | ||
|
|
||
| export default router; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.