Algolia 搜索集成
Algolia 是一个强大的搜索服务提供商,可以为你的 VitePress 站点提供快速、精准的搜索体验。
为什么选择 Algolia?
| 特性 | 本地搜索 | Algolia |
|---|---|---|
| 搜索速度 | 快 | 极快 |
| 搜索精度 | 一般 | 高(支持模糊匹配、同义词) |
| 搜索体验 | 基础 | 高级(高亮、分词、分页) |
| 多语言支持 | 基础 | 完善 |
| 分析统计 | 无 | 有 |
| 免费额度 | 无限 | 有(对开源项目免费) |
申请 Algolia
1. 注册账号
访问 Algolia 注册账号。
2. 创建应用
- 登录后点击 "Create Application"
- 选择免费计划(对开源项目有特殊优惠)
- 记录生成的 Application ID 和 Admin API Key
3. DocSearch 申请
对于开源文档站点,可以申请免费的 DocSearch 服务:
- 访问 DocSearch 申请页面
- 填写站点信息和邮箱
- 等待审核通过(通常 1-2 天)
- 收到包含配置信息的邮件
开源项目福利
如果你的项目是开源的,可以申请 DocSearch 免费服务。Algolia 会为你的站点配置爬虫并免费提供搜索服务。
配置 VitePress
方式一:使用 DocSearch
ts
// docs/.vitepress/config.mts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'your-index-name',
// 本地化配置
locales: {
'/': {
placeholder: '搜索文档',
translations: {
button: {
buttonText: '搜索',
buttonAriaLabel: '搜索文档'
},
modal: {
searchBox: {
resetButtonTitle: '清除查询',
resetButtonAriaLabel: '清除查询',
cancelButtonText: '取消',
cancelButtonAriaLabel: '取消'
},
startScreen: {
recentSearchesTitle: '搜索历史',
noRecentSearchesText: '没有搜索历史',
saveRecentSearchButtonTitle: '保存到搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除'
},
errorScreen: {
titleText: '无法获取结果',
helpText: '你可能需要检查网络连接'
},
footer: {
selectText: '选择',
navigateText: '切换',
closeText: '关闭',
searchByText: '搜索提供'
},
noResultsScreen: {
noResultsText: '没有找到相关结果',
suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为这个查询应该有结果?',
reportMissingResultsLinkText: '告诉我们'
}
}
}
}
}
}
}
}
})方式二:自定义配置
如果你有自己的 Algolia 应用:
ts
// docs/.vitepress/config.mts
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: 'XXXXXXXXXX',
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
indexName: 'vitepress',
// 搜索参数
searchParameters: {
facetFilters: ['language:zh-CN'] // 按语言过滤
},
// 分面配置
initialQuery: '', // 初始查询
// 调试模式
debug: false
}
}
}
})配置爬虫
DocSearch 配置文件
如果使用 DocSearch,需要提交配置文件:
json
{
"index_name": "your-index-name",
"start_urls": [
{
"url": "https://your-domain.com/",
"selectors_key": "default"
}
],
"stop_urls": [],
"selectors": {
"default": {
"lvl0": {
"selector": ".VPDoc h1",
"global": true,
"default_value": "Documentation"
},
"lvl1": ".VPDoc h1",
"lvl2": ".VPDoc h2",
"lvl3": ".VPDoc h3",
"lvl4": ".VPDoc h4",
"lvl5": ".VPDoc h5",
"text": ".VPDoc p, .VPDoc li",
"lang": {
"selector": "/html/@lang",
"type": "xpath",
"global": true
}
}
},
"selectors_exclude": [
".VPFooter",
".VPLocalNav"
],
"custom_settings": {
"attributesForFaceting": [
"language"
],
"separatorsToIndex": "_"
},
"conversation_id": ["your-conversation-id"],
"nb_hits": 1000
}自定义爬虫
使用 GitHub Actions 自动更新索引:
yaml
# .github/workflows/algolia-crawl.yml
name: Algolia Crawl
on:
push:
branches: [main]
schedule:
- cron: '0 3 * * *' # 每天 3:00 UTC
jobs:
crawl:
runs-on: ubuntu-latest
steps:
- name: Trigger Algolia Crawl
run: |
curl -X POST \
-H "Content-Type: application/json" \
-d '{"crawl": true}' \
"https://crawler.algolia.com/api/1/crawlers/YOUR_CRAWLER_ID/run?apiKey=${{ secrets.ALGOLIA_CRAWLER_API_KEY }}"高级配置
自定义搜索行为
ts
// docs/.vitepress/config.mts
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'your-index-name',
// 自定义搜索参数
searchParameters: {
// 每页结果数
hitsPerPage: 10,
// 要搜索的属性
restrictSearchableAttributes: ['title', 'content'],
// 按属性权重排序
attributesToSnippet: ['content:20'],
// 高亮配置
highlightPreTag: '<mark>',
highlightPostTag: '</mark>'
},
// 自定义转换函数
transformItems(items) {
return items.map(item => ({
...item,
// 自定义处理
url: item.url.replace('OLD_BASE', 'NEW_BASE')
}))
}
}
}
}
})多语言搜索
ts
// docs/.vitepress/config.mts
export default defineConfig({
locales: {
'/': { lang: 'zh-CN' },
'/en/': { lang: 'en-US' }
},
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: 'YOUR_APP_ID',
apiKey: 'YOUR_SEARCH_API_KEY',
indexName: 'your-index-name',
locales: {
'/': {
placeholder: '搜索文档',
translations: {
button: { buttonText: '搜索' },
modal: {
noResultsScreen: {
noResultsText: '没有找到结果'
}
}
}
},
'/en/': {
placeholder: 'Search docs',
translations: {
button: { buttonText: 'Search' },
modal: {
noResultsScreen: {
noResultsText: 'No results found'
}
}
}
}
}
}
}
}
})自定义搜索组件
替换默认搜索按钮
vue
<!-- docs/.vitepress/theme/components/CustomSearch.vue -->
<script setup lang="ts">
import { ref } from 'vue'
const openSearch = () => {
// 触发 Algolia 搜索弹窗
const searchButton = document.querySelector('.DocSearch-Button')
if (searchButton) {
searchButton.click()
}
}
</script>
<template>
<button class="custom-search" @click="openSearch">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg>
<span>搜索文档</span>
<kbd>⌘K</kbd>
</button>
</template>
<style scoped>
.custom-search {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--vp-c-bg-soft);
border: 1px solid var(--vp-c-divider);
border-radius: 8px;
cursor: pointer;
transition: all 0.25s ease;
}
.custom-search:hover {
border-color: var(--vp-c-brand-1);
}
.custom-search span {
color: var(--vp-c-text-2);
}
.custom-search kbd {
padding: 2px 6px;
background: var(--vp-c-divider);
border-radius: 4px;
font-size: 12px;
color: var(--vp-c-text-3);
}
</style>样式自定义
自定义搜索弹窗样式
css
/* docs/.vitepress/theme/style.css */
/* 搜索按钮样式 */
.DocSearch-Button {
background: var(--vp-c-bg-soft) !important;
border: 1px solid var(--vp-c-divider) !important;
border-radius: 8px !important;
}
.DocSearch-Button:hover {
border-color: var(--vp-c-brand-1) !important;
}
/* 搜索弹窗样式 */
.DocSearch-Modal {
border-radius: 12px !important;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2) !important;
}
/* 搜索结果高亮 */
.DocSearch-Highlight {
background: var(--vp-c-brand-soft) !important;
color: var(--vp-c-brand-1) !important;
padding: 0 2px;
border-radius: 2px;
}
/* 搜索结果项 */
.DocSearch-Hit {
border-radius: 8px !important;
}
.DocSearch-Hit:hover {
background: var(--vp-c-default-soft) !important;
}
/* 深色模式 */
html.dark .DocSearch-Modal {
background: var(--vp-c-bg) !important;
}
html.dark .DocSearch-Footer {
background: var(--vp-c-bg-soft) !important;
}搜索分析
查看搜索统计
Algolia 提供了丰富的分析功能:
- 登录 Algolia Dashboard
- 选择你的应用和索引
- 进入 "Analytics" 页面
可以查看:
- 搜索次数
- 热门搜索词
- 无结果搜索词
- 点击率统计
使用分析数据优化
根据搜索数据优化你的文档:
- 无结果搜索词:添加缺失的内容
- 热门搜索词:优化相关页面的 SEO
- 点击率低的词:改进搜索结果排名
常见问题
搜索结果不准确
检查索引配置:
- 确保 selectors 配置正确
- 检查页面结构是否匹配
- 验证爬虫是否正常工作
搜索速度慢
优化建议:
- 减少搜索的属性数量
- 使用
restrictSearchableAttributes - 启用缓存
多语言搜索问题
确保:
- 每个语言有正确的
lang属性 - 使用
facetFilters按语言过滤 - 配置正确的 locales