Algolia, 一款开箱即用的网站搜索组件
约 833 字大约 3 分钟...
摘要
本文将介绍如何使用Algolia为网站增加搜索功能, 此处以VuePress的博客网站为例。
提交申请
Algolia使用之前需要向官网提交申请, 申请链接:
https://docsearch.algolia.com/apply/
提交申请后既可耐心等待, 官网需要1~3天时间进行审查, 通过审查后即可收到官网发送的邮件通知, 收到以下内容的邮件即代表通过审核可以进行下一步操作。
Hello again,
Congratulations! Your search is now ready. We've prepared your DocSearch app, please follow the steps below:
DocSearch uses the Algolia hosted crawler to insert records found on your website into your Algolia index. The crawler has already been started automatically!
- Once you accept the invitation below, you:
-- May be prompted to go through an upload data step. If so, use the Algolia provided sample data and complete the process.
-- Otherwise, you'll be brought to the Algolia dashboard.
- Note that the "Getting Started" page accessed from the dashboard home page does not apply to DocSearch users.
- If you need to make changes to the crawler:
-- You can access the crawler from dashboard.algolia.com->data sources->crawler->click on your crawler
-- Note - While you are able to, please do not delete the crawler or create a new one.
Accept this invitation to get started!
导入组件相关代码
此处以Vuepress-Theme-Hope主题的博客网站为例, 与VuePress大同小异。
// 在 `theme.ts` 文件的 plugins 中增加以下代码
// `indexName`: Algolia中配置的名称
// `appId`: Algolia首页的Application ID
// `apiKey`: Algolia首页的Search API Key [该key可以公开使用]
docsearch: {
indexName: "richelf",
appId: "A8B8L156RC",
apiKey: "6ca6a4e3763d4a19343e2b6494fcb613",
}
配置Algolia数据服务(运行官方爬虫)
- 进入Algolia的控制台https://dashboard.algolia.com/, 在导航栏选择与上文
indexName
对应的应用, 并点击Go To Crawler按钮。
// 根据网站的 `html` 结构修改 `actions` 中的 `recordProps` 内容
// 例如: 需要检索的内容在 `.vp-page` 类中的 `p, li, a, td, span` 标签,
// 则可以与示例代码保持一致。
actions: [
{
indexName: "richelf",
pathsToMatch: ["https://richelf.tech/**"],
recordExtractor: ({ $, helpers }) => {
return helpers.docsearch({
recordProps: {
lvl0: {
selectors: ".vp-sidebar-heading.active",
defaultValue: "Documentation",
},
lvl1: ".vp-page h1",
lvl2: ".vp-page h2",
lvl3: ".vp-page h3",
lvl4: ".vp-page h4",
lvl5: ".vp-page h5",
lvl6: ".vp-page h6",
content: ".vp-page p, .vp-page li, .vp-page a, .vp-page td, .vp-page span",
lang: "",
tags: {
defaultValue: ["v1"],
},
},
indexHeadings: true,
aggregateContent: true,
});
},
},
],
- 配置完毕后点击右上角
Save
按钮进行保存, 并点击Start Crawl
建立数据映射, 至此Algolia的配置就完成了。
Powered by Waline v3.3.0