关于 Algolia 的使用技巧

了解如何在 FixIt 主题中使用 algolia,并自动化更新索引。
创建 Algolia 应用
- 注册 algolia 账号
- 在 algolia 中创建一个应用(Application),例如 fixit-blog
- 选中应用 fixit-blog=> 点击Data Sources=> 点击Indices=> 点击Create Index
- 创建一个索引,例如 index.zh-cn
- 点击 Settings=> 点击API Keys=> 复制保存 API Keys- Application ID
- Search-Only API Key
- Admin API Key(请勿公开)
 
Application ID 和 Search-Only API Key 用于搜索配置,Admin API Key 用于自动化更新索引。
FixIt 中的搜索配置
根据上一步获取到的 API Keys,配置 algolia 的搜索功能,你需要在站点配置中添加以下内容。
|  |  | 
为了生成搜索功能所需要的 index.json, 请在你的站点配置中添加 JSON 输出文件类型到 outputs 部分的 home 字段中。
|  |  | 
上传索引
然后你需要上传 index.json 到 algolia 来激活搜索功能。你可以使用浏览器来上传 index.json 文件,但是一个自动化的脚本可能效果更好,Algolia Atomic 是一个不错的选择。
index.json 文件到对应的 algolia index, 例如 zh-cn/index.json 或 fr/index.json……准备
请确保你已经安装了 Node.js。
安装 Algolia Atomic
如果你的项目中没有 package.json 文件,请先创建一个。
|  |  | 
然后安装 Algolia Atomic。
|  |  | 
在 package.json 文件中添加以下内容。
|  |  | 
使用
当你执行 hugo 命令生成站点后,你可以使用以下命令上传 index.json 文件到 algolia 来更新索引。
|  |  | 
- ALGOLIA_APP_ID:algolia Application ID
- ALGOLIA_ADMIN_KEY:algolia Admin API Key
- ALGOLIA_INDEX_NAME:algolia 索引名称
- ALGOLIA_INDEX_FILE:本地 index.json文件路径
自动化更新索引
One more thing,你可以使用 GitHub Actions 自动执行将 index.json 上传到 algolia 的过程。
- 在你的 GitHub 仓库中添加一个 - ALGOLIA_ADMIN_KEY的 secret,值为 algolia Admin API Key。
- 在你的 GitHub 仓库中添加一个 - .github/workflows/algolia-atomic.yml文件,内容如下。- 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- name: Update Algolia Search Index on: push: branches: - master paths: - "content" workflow_dispatch: jobs: algolia-atomic: runs-on: ubuntu-latest steps: - name: Check out repository code uses: actions/checkout@v4 with: submodules: recursive # Fetch Hugo themes (true OR recursive) fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod - name: Setup Hugo uses: peaceiris/actions-hugo@v2 with: hugo-version: "latest" extended: true - name: Build run: | npm install npm run build - name: Update Algolia Index (en) env: ALGOLIA_APP_ID: YKOxxxxLUY # algolia Application ID ALGOLIA_ADMIN_KEY: ${{ secrets.ALGOLIA_ADMIN_KEY }} # algolia Admin API Key ALGOLIA_INDEX_NAME: "index.en" # algolia index name ALGOLIA_INDEX_FILE: './public/index.json' # local index.json file path run: | npm run algolia - name: Update Algolia Index (zh-cn) env: ALGOLIA_APP_ID: YKOxxxxLUY ALGOLIA_ADMIN_KEY: ${{ secrets.ALGOLIA_ADMIN_KEY }} ALGOLIA_INDEX_NAME: "index.zh-cn" ALGOLIA_INDEX_FILE: "./public/zh-cn/index.json" run: | npm run algolia
- 当你将你的站点推送到 GitHub 仓库的 - master分支时,GitHub Actions 将自动执行- hugo命令生成站点,并将- index.json上传到 algolia。
🎉 现在,一切准备就绪了!
