为 Nobelium 博客集成 Algolia DocSearch
date
Jan 6, 2023
slug
integrate-algolia-docsearch-with-nobelium-blog
status
Published
tags
life
BlogOps
summary
type
Post
前言
Nobelium 博客的使用体验很好,但在搜索功能上,我眼馋各种使用 Algolia DocSearch 的网站那“一步直达”的搜索体验,于是研究了一下在自己的博客上实装。

安装
首先注册 Algolia 账户并创建一个 Application.

因为使用 current 版本的 Algolia DocSearch 需要提交申请,对网站内容有要求并且时间比较漫长,故选择可自行部署的 legacy 版本(已停止维护,但仍然可用)
接下来只要做两件事:①运行官方提供的爬虫,爬取网站内容并上传至 Algolia;②将 SearchBox 组件代码添加到 Nobelium 中。
爬取网站内容
参考官方文档,本文使用 Docker 镜像运行爬虫。
配置环境变量
方便起见,可以创建
.env
文件存放 API KEY. 此处的 API_KEY 需具有写权限,应使用 Admin API Key. (Please keep it secret and use it ONLY from your backend)APPLICATION_ID=YOUR_APP_ID
API_KEY=YOUR_API_KEY
编写配置文件
针对 Nobelium 生成的网站,我摸索出的 selectors 如下,作为参考:
{
"index_name": "example",
"start_urls": ["https://<Your Domain>"],
"stop_urls": [
"https://<Your Domain>/tag/*",
"https://<Your Domain>/feed",
"https://<Your Domain>/search",
"https://<Your Domain>/playground",
"https://<Your Domain>/experiment"
],
"sitemap_urls": [
"https://<Your Domain>/sitemap.xml"
],
"selectors": {
"lvl0": "article h1",
"lvl1": ".notion-h1",
"lvl2": ".notion-h2",
"lvl3": ".notion-h3",
"text": "div.notion-text, .notion-bookmark-title, .notion-bookmark-link, blockquote, .notion-list"
}
}
存在的缺陷:没有覆盖到行内链接。
关于配置文件的更详细说明请查阅官方文档。
运行 Docker 镜像
首先需要安装 jq,用于解析 JSON.
然后执行此命令(因为爬取是一次性的,建议添加
--rm
参数,退出后自动删除)docker run -it --env-file=.env -e "CONFIG=$(cat /path/to/your/config.json | jq -r tostring)" algolia/docsearch-scraper
结果如图:

在 Algolia Dashboard 上检查结果是否符合自己的要求:

添加搜索 UI
Algolia 提供了开箱即用的组件。
参考修改方法如下:
安装
@docsearch/react
yarn add @docsearch/react@3
修改
components/Header.js
import { useEffect, useRef } from 'react'
...
import { DocSearch } from '@docsearch/react' // 1. 添加导入
import '@docsearch/css'
const NavBar = () => {
const links = [
{ id: 0, name: 'Blog', to: BLOG.path || '/', show: true },
{ id: 1, name: 'About', to: '/about', show: BLOG.showAbout },
{ id: 2, name: 'RSS', to: '/feed', show: true }
// { id: 3, name: locale.NAV.SEARCH, to: '/search', show: true } // 2. 注释掉原来的搜索按钮或者改 show:false
]
return (
<div className="flex-shrink-0">
<ul className="flex flex-row items-center"> // 3. 添加 items-center 类
{links.map(...)}
<DocSearch // 4. 添加 DocSearch 组件
appId="YOUR_APP_ID"
indexName="YOUR_INDEX_NAME"
apiKey="YOUR_SEARCH_API_KEY"
/>
</ul>
</div>
)
}
...
成果展示

自动化
待补充