Algolia DocSearch
Docusaurus 提供了多種方式讓你的網站可以搜尋文件, 詳細可以參考文件, 這邊記錄如何透過 Algolia 提供的 DocSearch 服務來實作搜尋功能
1. 先至官網申請註冊, 取得 API Key
註冊完後會直接讓你先取一個 db index name, 這個名稱是用來標示你的搜尋資料庫的名稱, 之後會用到
create index 完後下面的可以先不管, 因為待會我們會直接將資料爬進來
然後可以直接點回首頁, 就會看到你的 Application ID
和 Write API Key
假設你之前已經註冊並使用過, 會長不一樣的介面
然後你就可以看到其實一開始預設給你的 Key 提供的功能很多, 假設你不需要那麼多可以自己建立一個新的 Key, 並設定所需要的即可
2. 安裝 DocSearch
因為使用 @docusaurus/preset-classic
, 本身已經內建 Algolia 相關的了, 所以直接可以使用, 在 docusaurus.config.js
中加入以下設定
docusaurus.config.js
module.exports = {
// ...
algolia: {
apiKey: process.env.API_KEY,
indexName: process.env.INDEX_NAME,
appId: process.env.APPLICATION_ID
}
};
設定完之後, 在網頁右上角就會多出一個搜尋框可以使用, 只是目前會搜尋不到任何資訊, 因為我們還沒將資料放進 Algolia 中
3. 將資料放進 Algolia
DOCSearch 有改版, 要使用一連串的功能需要先 apply, 並且符合以下條件:
因為放這文件的 repo 本身還沒弄完, 還沒 publish, 所以暫時沒有申請, 就先使用舊版的方式
- 設定 .env
APPLICATION_ID=YOUR_APP_ID
API_KEY=YOUR_API_KEY - 設定 config.json (詳細可參考此)
{
"index_name": "jimcat-dev",
"start_urls": ["https://docs.jimcat.dev"],
"sitemap_urls": ["https://docs.jimcat.dev/sitemap.xml"],
"sitemap_alternate_links": true,
"stop_urls": ["/tests"],
"selectors": {
"lvl0": {
"selector": "(//ul[contains(@class,'menu__list')]//a[contains(@class, 'menu__link menu__link--sublist menu__link--active')]/text() | //nav[contains(@class, 'navbar')]//a[contains(@class, 'navbar__link--active')]/text())[last()]",
"type": "xpath",
"global": true,
"default_value": "Documentation"
},
"lvl1": "header h1",
"lvl2": "article h2",
"lvl3": "article h3",
"lvl4": "article h4",
"lvl5": "article h5, article td:first-child",
"lvl6": "article h6",
"text": "article p, article li, article td:last-child"
},
"strip_chars": " .,;:#",
"custom_settings": {
"separatorsToIndex": "_",
"attributesForFaceting": ["language", "version", "type", "docusaurus_tag"],
"attributesToRetrieve": ["hierarchy", "content", "anchor", "url", "url_without_anchor", "type"]
},
"conversation_id": ["833762294"],
"nb_hits": 46250
}
-
使用官方的 docker image (在 windows 環境下的 CMD 可能會遇到無法使用指令, 可以改使用 git 的 bash cmd 來操作)
docker run -it --env-file=.env -e "CONFIG=$(cat /path/to/your/config.json)" algolia/docsearch-scraper
這時候在 Algolia 的 index 中就會看到資料了
現在網頁上的搜尋功能就能搜尋到資料了
ref: