-
Notifications
You must be signed in to change notification settings - Fork 37
[WIP]: Investigate algolia as a search replacement #2333
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
Draft
jackw
wants to merge
16
commits into
main
Choose a base branch
from
jackhugo/algolia-search
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
fba79a0
wip: initial
hugohaggmark 2718c11
feat(website): minor progress on search
jackw 9c5936d
ci(dev-portal): test running server
jackw 1c621d9
ci(dev-portal): more testing
jackw 9d5d722
ci(dev-portal): use ampersand to run additional steps
jackw 85324be
ci(dev-portal): more trying to get a server
jackw 598aa0c
feat(website): split crawler into crawl n upload
jackw 6d75673
feat(website): do a bit of crawling, generate some records
jackw 88d7f61
build(website): fix a few bugs in the crawlers record generation
jackw b5d5204
build(website): fix issue with lvl0 not matching top level sidebar item
jackw 683f0d1
feat(website): rewrite sitemap urls for dev and prod builds
jackw df9e674
feat(website): create unique object ids from heading levels
jackw d7fa812
feat(website): create separate records for headings and content for b…
jackw 403a5c1
feat(website): add script to upload to algolia
jackw 4199f80
revert(ci): put back dev portal dev deploy for testing
jackw 8ea0de6
revert(website): put back dev / prod env file in docusaurus config
jackw 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
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
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
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
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
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
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,236 @@ | ||
| import { type CheerioAPI, CheerioCrawler, type LoadedRequest, type Request, log, LogLevel, Sitemap } from 'crawlee'; | ||
| import { createHash } from 'node:crypto'; | ||
| import { inspect } from 'util'; | ||
| import { type DocSearchRecord } from './types.ts'; | ||
|
|
||
| log.setLevel(LogLevel.INFO); | ||
|
|
||
| function generateAlgoliaRecords(request: LoadedRequest<Request>, $: CheerioAPI) { | ||
| const version = $('meta[name="docsearch:version"]').attr('content') || 'current'; | ||
| const lang = $('meta[name="docsearch:lang"]').attr('content') || 'en'; | ||
| const docusaurus_tag = $('meta[name="docsearch:docusaurus_tag"]').attr('content') || 'default'; | ||
| let position = 0; | ||
| const lvl0 = | ||
| $( | ||
| '.menu__link.menu__link--active, menu__link.menu__link--sublist.menu__link--active, .navbar__item.navbar__link--active' | ||
| ) | ||
| .last() | ||
| .text() || 'Documentation'; | ||
|
|
||
| // Helper function to extract heading hierarchy records | ||
| function extractHeadingLevel(level: number, positionRef: { current: number }) { | ||
| const selector = level === 1 ? 'header h1, article h1' : `article h${level}`; | ||
| let elements = $(selector); | ||
|
|
||
| // Special filter for h3 elements to exclude "Was this page helpful?" | ||
| if (level === 3) { | ||
| elements = elements.filter((_, el) => $(el).text() !== 'Was this page helpful?'); | ||
| } | ||
|
|
||
| const records: DocSearchRecord[] = []; | ||
|
|
||
| elements.each((_, el) => { | ||
| // Build hierarchy (same logic as before) | ||
| const hierarchy: DocSearchRecord['hierarchy'] = { | ||
| lvl0, | ||
| lvl1: null, | ||
| lvl2: null, | ||
| lvl3: null, | ||
| lvl4: null, | ||
| lvl5: null, | ||
| lvl6: null, | ||
| }; | ||
| if (level === 1) { | ||
| hierarchy.lvl1 = $(el).text(); | ||
| for (let i = 2; i <= 6; i++) { | ||
| hierarchy[`lvl${i}`] = null; | ||
| } | ||
| } else { | ||
| hierarchy.lvl1 = $(el).closest('article').find('header h1, > h1').first().text(); | ||
| for (let i = 2; i < level; i++) { | ||
| hierarchy[`lvl${i}`] = $(el).prevAll(`h${i}`).first().text() || null; | ||
| } | ||
| hierarchy[`lvl${level}`] = $(el).text(); | ||
| } | ||
|
|
||
| // Calculate URL (same as before) | ||
| const prodUrl = new URL(request.url); | ||
| prodUrl.host = 'grafana.com'; | ||
| prodUrl.protocol = 'https'; | ||
| prodUrl.port = ''; | ||
|
|
||
| const anchor = $(el).attr('id') ?? null; // Changed: null instead of '' | ||
| const url = `${prodUrl.toString()}${anchor ? `#${anchor}` : ''}`; | ||
|
|
||
| // Generate objectID | ||
| const objectID = createHash('sha256') | ||
| .update(Object.values(hierarchy).filter(Boolean).join('-') + `-lvl${level}-${positionRef.current}`) | ||
| .digest('hex'); | ||
|
|
||
| // Create heading record | ||
| const headingRecord: DocSearchRecord = { | ||
| objectID, | ||
| type: `lvl${level}` as DocSearchRecord['type'], | ||
| hierarchy, | ||
| content: null, // Headings have no content | ||
| url, | ||
| url_without_anchor: prodUrl.toString(), | ||
| anchor, | ||
| weight: { | ||
| ...calculateWeight({ url, type: `lvl${level}` as DocSearchRecord['type'] }), | ||
| position: positionRef.current++, | ||
| }, | ||
| version, | ||
| lang, | ||
| language: lang, | ||
| docusaurus_tag, | ||
| }; | ||
|
|
||
| records.push(headingRecord); | ||
|
|
||
| // Find content under this heading | ||
| const allBetweenHeadings = $(el).nextUntil(`h1,h2,h3,h4,h5,h6`); | ||
| const contentElements = allBetweenHeadings | ||
| .filter('p, li, td:last-child') // Check the elements themselves | ||
| .add(allBetweenHeadings.find('p, li, td:last-child')) // Check descendants | ||
| .toArray(); | ||
|
|
||
| if (contentElements.length > 0) { | ||
| const contentText = contentElements | ||
| .map((el) => $(el).text().trim()) | ||
| .filter(Boolean) | ||
| .join(' '); | ||
|
|
||
| if (contentText) { | ||
| const contentObjectID = createHash('sha256') | ||
| .update(Object.values(hierarchy).filter(Boolean).join('-') + `-content-${positionRef.current}`) | ||
| .digest('hex'); | ||
|
|
||
| const contentRecord: DocSearchRecord = { | ||
| objectID: contentObjectID, | ||
| type: 'content', | ||
| hierarchy, | ||
| content: contentText, | ||
| url, | ||
| url_without_anchor: prodUrl.toString(), | ||
| anchor, | ||
| weight: { | ||
| ...calculateWeight({ url, type: 'content' }), | ||
| position: positionRef.current++, | ||
| }, | ||
| version, | ||
| lang, | ||
| language: lang, | ||
| docusaurus_tag, | ||
| }; | ||
|
|
||
| records.push(contentRecord); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| return records; | ||
| } | ||
|
|
||
| const positionRef = { current: position }; | ||
| const lvl1 = extractHeadingLevel(1, positionRef); | ||
| const lvl2 = extractHeadingLevel(2, positionRef); | ||
| const lvl3 = extractHeadingLevel(3, positionRef); | ||
| const lvl4 = extractHeadingLevel(4, positionRef); | ||
| const lvl5 = extractHeadingLevel(5, positionRef); | ||
| const lvl6 = extractHeadingLevel(6, positionRef); | ||
|
|
||
| const parsedUrl = new URL(request.url); | ||
| const basePath = '/developers/plugin-tools/'; | ||
| let pathname = parsedUrl.pathname; | ||
|
|
||
| if (pathname.startsWith(basePath)) { | ||
| pathname = pathname.slice(basePath.length); | ||
| } | ||
|
|
||
jackw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const hierarchy = [...lvl1, ...lvl2, ...lvl3, ...lvl4, ...lvl5, ...lvl6]; | ||
| return hierarchy; | ||
| } | ||
|
|
||
| function generateObjectId(request: LoadedRequest<Request>) { | ||
| const parsedUrl = new URL(request.url); | ||
| const basePath = '/developers/plugin-tools/'; | ||
| let pathname = parsedUrl.pathname; | ||
|
|
||
| if (pathname.startsWith(basePath)) { | ||
| pathname = pathname.slice(basePath.length); | ||
| } | ||
| const segments = pathname.split('/').filter(Boolean); | ||
| return segments.length > 0 ? `${segments.join('_')}` : `index`; | ||
| } | ||
|
|
||
| const levelWeights = { | ||
| lvl0: 100, | ||
| lvl1: 100, | ||
| lvl2: 90, | ||
| lvl3: 80, | ||
| lvl4: 70, | ||
| lvl5: 60, | ||
| lvl6: 50, | ||
| content: 0, | ||
| }; | ||
|
|
||
| const basePath = '/developers/plugin-tools/'; | ||
|
|
||
| function calculateWeight({ url, type }: { url: string; type: DocSearchRecord['type'] }) { | ||
| const pathname = new URL(url).pathname; | ||
| const pathnameWithoutBasePath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname; | ||
| const depth = pathnameWithoutBasePath.split('/').filter(Boolean).length; | ||
| const pageRank = Math.max(0, 110 - depth * 10); | ||
| return { | ||
| pageRank, | ||
| level: levelWeights[type], | ||
| }; | ||
| } | ||
|
|
||
| const crawler = new CheerioCrawler({ | ||
| // The crawler downloads and processes the web pages in parallel, with a concurrency | ||
| // automatically managed based on the available system memory and CPU (see AutoscaledPool class). | ||
| // Here we define some hard limits for the concurrency. | ||
| minConcurrency: 10, | ||
| maxConcurrency: 50, | ||
| // On error, retry each page at most once. | ||
| maxRequestRetries: 1, | ||
|
|
||
| // Increase the timeout for processing of each page. | ||
| requestHandlerTimeoutSecs: 30, | ||
|
|
||
| // maxRequestsPerCrawl: 10, | ||
|
|
||
| // This function will be called for each URL to crawl. | ||
| // It accepts a single parameter, which is an object with options as: | ||
| // https://crawlee.dev/js/api/cheerio-crawler/interface/CheerioCrawlerOptions#requestHandler | ||
| // We use for demonstration only 2 of them: | ||
| // - request: an instance of the Request class with information such as the URL that is being crawled and HTTP method | ||
| // - $: the cheerio object containing parsed HTML | ||
| async requestHandler({ pushData, request, $ }) { | ||
| log.info(`Processing ${request.url}...`); | ||
| const result = generateAlgoliaRecords(request, $); | ||
| log.debug(inspect(result, { depth: null, colors: true })); | ||
| const objectID = generateObjectId(request); | ||
| await pushData(result, objectID); | ||
| }, | ||
|
|
||
| // This function is called if the page processing failed more than maxRequestRetries + 1 times. | ||
| failedRequestHandler({ request }) { | ||
| log.warning(`Request ${request.url} failed twice.`); | ||
| }, | ||
| }); | ||
|
|
||
| const { urls } = await Sitemap.load('http://localhost:3000/developers/plugin-tools/sitemap.xml'); | ||
| const localhostUrls = urls | ||
| .filter((url: string) => !url.endsWith('/search')) | ||
| .map((url: string) => url.replace(/https:\/\/grafana(-dev)?\.com/, 'http://localhost:3000')); | ||
|
|
||
| await crawler.run(localhostUrls); | ||
|
|
||
| // Can pass individual urls for testing purposes. | ||
| // const url = ['http://localhost:3000/developers/plugin-tools/how-to-guides/extend-configurations/']; | ||
| // await crawler.run(url); | ||
|
|
||
| log.info('Crawler finished.'); | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This could disable the search page completely if we want to. We don't have one in prod today 👍