{"title":"添加typesense搜索","slug":"f287c563","url":"https://blog.biss.click/posts/f287c563/","date":"2026-02-05T13:14:16.000Z","updated":null,"summary":"这篇文章介绍了如何在博客中集成Typesense搜索引擎,包括安装Typesense、添加数据集以及同步数据的详细步骤。首先,通过命令行安装Typesense并配置相关参数,如API密钥和数据目录。接着,安装必要的npm包,并在Hexo博客中配置搜索功能,指定存储搜索数据的JSON文件路径。然后,编写了一个同步脚本,用于读取XML文件、解析数据、检查或创建集合以及导入数据到Typesense。最后,在博客底部添加了InstantSearch和Typesense的JavaScript库,并根据实际情况修改了配置。","tags":[],"categories":["技术","建站手札"],"series":"webcustom","seriesOrder":null,"contentFormat":"text/markdown","content":"{% note warning %}\n注意:本文为早期 Hexo / Butterfly 魔改记录,本站现已迁移到 Astro,相关代码、路径或插件可能已经失效,仅作历史参考。\n{% endnote %}\n\n最近在构建班级博客,用```ghost cms```,在构建搜索时发现了typesense,所以把他移植到这个博客上。\n\n# 安装typesense\n\n直接用```docker-compose```:\n\n```yaml\n\nservices:\n typesense:\n image: typesense/typesense:30.1\n restart: always\n ports:\n - \"8108:8108\"\n volumes:\n - ./typesense-data:/data\n command: '--data-dir /data --api-key=填写key --enable-cors'\n\n```\n\n然后就是反向代理之类的,不过多写了。\n\n# 添加数据集\n\n```bash\n# 先安装库\nnpm install hexo-generator-search\nnpm install typesense xml2js\n```\n然后在```config.yml```配置(就是把文章生成json):\n\n```yml\nsearch:\n path: search.json\n field: post\n content: true\n```\n\n创建一个数据同步脚本```sync_typesense.js```:\n\n```js\nconst Typesense = require('typesense');\nconst fs = require('fs');\nconst xml2js = require('xml2js');\n\n// --- 配置区域 ---\nconst CONFIG = {\n apiKey: '你的Admin-API-Key', // 必须是 Admin Key\n host: '你的Typesense主机地址', \n port: 443,\n protocol: 'https',\n collectionName: 'blogs'\n};\n\nconst client = new Typesense.Client({\n 'nodes': [{ 'host': CONFIG.host, 'port': CONFIG.port, 'protocol': CONFIG.protocol }],\n 'apiKey': CONFIG.apiKey,\n 'connectionTimeoutSeconds': 5\n});\n\nasync function sync() {\n try {\n // 1. 读取并解析 XML\n const xml = fs.readFileSync('./public/search.xml', 'utf8');\n const parser = new xml2js.Parser({ explicitArray: false });\n const result = await parser.parseStringPromise(xml);\n \n // 提取文章列表 (处理单篇文章和多篇文章的情况)\n let entries = result.search.entry;\n if (!Array.isArray(entries)) entries = [entries];\n\n // 格式化数据以适配 Typesense\n const documents = entries.map(post => ({\n title: post.title,\n url: post.url,\n content: post.content,\n categories: post.categories ? (Array.isArray(post.categories.category) ? post.categories.category : [post.categories.category]) : [],\n tags: post.tags ? (Array.isArray(post.tags.tag) ? post.tags.tag : [post.tags.tag]) : [],\n }));\n\n // 2. 检查或创建 Collection (Schema)\n try {\n await client.collections(CONFIG.collectionName).retrieve();\n } catch (err) {\n const schema = {\n name: CONFIG.collectionName,\n fields: [\n { name: 'title', type: 'string', locale: 'zh'},\n { name: 'content', type: 'string', locale: 'zh'},\n { name: 'url', type: 'string' },\n { name: 'categories', type: 'string[]', facet: true },\n { name: 'tags', type: 'string[]', facet: true }\n ]\n };\n await client.collections().create(schema);\n console.log('Collection created!');\n }\n\n // 3. 导入数据 (使用 upsert 模式:存在则更新,不存在则创建)\n console.log(`Syncing ${documents.length} posts to Typesense...`);\n await client.collections(CONFIG.collectionName).documents().import(documents, { action: 'upsert' });\n console.log('Sync complete!');\n\n } catch (error) {\n console.error('Sync failed:', error);\n }\n}\n\nsync();\n```\n然后运行```node sync_typesense.js```\n\n# 创建只读key\n把下面代码存储成js,node运行就行。\n```js\nconst http = require('https');\n\nconst data = JSON.stringify({\n \"description\": \"Public search only key\",\n \"actions\": [\"documents:search\"],\n \"collections\": [\"blogs\"]\n});\n\nconst options = {\n hostname: '', // 不要带 https://\n port: 443,\n path: '/keys',\n method: 'POST',\n headers: {\n 'X-TYPESENSE-API-KEY': '你的admin key',\n 'Content-Type': 'application/json',\n 'Content-Length': data.length\n }\n};\n\nconst req = http.request(options, res => {\n res.on('data', d => { process.stdout.write(d); });\n});\n\nreq.on('error', error => { console.error(error); });\nreq.write(data);\nreq.end();\n```\n\n# 博客添加搜索\n\n在```config.yaml```inject bottom添加:\n\n```yaml\n - \n - \n```\n\n为了方便,我直接修改了```\\themes\\butterfly\\source\\js\\search\\local_search.js```\n\n```js\n(function () {\n 'use strict';\n\n // ============================================================================\n // 配置区域 - 请根据实际情况修改\n // ============================================================================\n const CONFIG = {\n apiKey: \"\", // ⚠️ 建议使用 Search-Only API Key\n server: {\n host: \"host\",\n port: \"443\",\n protocol: \"https\"\n },\n indexName: \"blogs\",\n searchParams: {\n query_by: \"title,content\",\n highlight_full_fields: \"title,content\",\n per_page: 8,\n num_typos: 1,\n typo_tokens_threshold: 1,\n prefix: true\n },\n ui: {\n maxRetries: 10,\n retryDelay: 100,\n animationDuration: 300\n }\n };\n\n // ============================================================================\n // 状态管理\n // ============================================================================\n let searchInstance = null;\n let isInitialized = false;\n let isSearchOpen = false;\n let initRetryCount = 0;\n const MAX_INIT_RETRIES = 30; // 最多重试30次 (3秒)\n\n // ============================================================================\n // 错误提示函数\n // ============================================================================\n function showErrorMessage() {\n const hitsContainer = document.getElementById('hits');\n if (!hitsContainer) return;\n \n hitsContainer.innerHTML = \n '
' +\n '
' +\n '
搜索服务加载失败
' +\n '
' +\n '

依赖库未能正确加载,请检查以下配置:

' +\n '
    ' +\n '
  1. 确认已在 _config.butterfly.yml 中正确引入依赖
  2. ' +\n '
  3. 检查 JS 文件加载顺序(先 instantsearch.js,再 adapter)
  4. ' +\n '
  5. 尝试更换 CDN 或使用本地文件
  6. ' +\n '
  7. 打开浏览器控制台查看详细错误信息
  8. ' +\n '
' +\n '
' +\n '
' +\n '' +\n '
' +\n '
';\n }\n\n // ============================================================================\n // 1. 动态插入 HTML 结构\n // ============================================================================\n const searchHTML = `\n
\n
\n
\n \n 本站搜索\n \n ×\n
\n
\n
\n
\n
\n
\n Search powered by Typesense\n
\n
\n
\n\n \n `;\n\n document.body.insertAdjacentHTML('beforeend', searchHTML);\n\n const mask = document.getElementById('typesense-search-mask');\n const closeBtn = document.getElementById('close-typesense');\n const container = document.getElementById('typesense-search-container');\n\n // ============================================================================\n // 搜索控制\n // ============================================================================\n function openSearch() {\n if (isSearchOpen) return;\n isSearchOpen = true;\n mask.style.display = 'block';\n void mask.offsetWidth;\n mask.classList.add('active');\n document.body.style.overflow = 'hidden';\n\n if (!isInitialized) {\n initTypesense();\n }\n focusSearchInput();\n }\n\n function closeSearch() {\n if (!isSearchOpen) return;\n isSearchOpen = false;\n mask.classList.remove('active');\n setTimeout(function() {\n mask.style.display = 'none';\n document.body.style.overflow = '';\n }, CONFIG.ui.animationDuration);\n }\n\n function focusSearchInput(retryCount) {\n retryCount = retryCount || 0;\n const input = document.querySelector('.ais-SearchBox-input');\n if (input) {\n input.focus();\n input.select();\n } else if (retryCount < CONFIG.ui.maxRetries) {\n setTimeout(function() {\n focusSearchInput(retryCount + 1);\n }, CONFIG.ui.retryDelay);\n }\n }\n\n // ============================================================================\n // 事件监听\n // ============================================================================\n document.addEventListener('click', function(e) {\n if (e.target.closest('.search-typesense-trigger')) {\n e.preventDefault();\n openSearch();\n }\n });\n\n closeBtn.addEventListener('click', closeSearch);\n mask.addEventListener('click', function(e) {\n if (e.target === mask) closeSearch();\n });\n container.addEventListener('click', function(e) {\n e.stopPropagation();\n });\n window.addEventListener('keydown', function(e) {\n if (e.key === 'Escape' && isSearchOpen) {\n closeSearch();\n }\n if ((e.ctrlKey || e.metaKey) && e.key === 'k') {\n e.preventDefault();\n openSearch();\n }\n });\n\n // ============================================================================\n // Typesense 初始化(带重试限制)\n // ============================================================================\n function initTypesense() {\n if (isInitialized || searchInstance) {\n console.warn('Typesense 搜索已初始化');\n return;\n }\n\n var instantsearchLoaded = typeof instantsearch !== 'undefined';\n var adapterLoaded = typeof TypesenseInstantSearchAdapter !== 'undefined' || \n typeof window.TypesenseInstantSearchAdapter !== 'undefined';\n \n console.log('📦 依赖库检查 (' + (initRetryCount + 1) + '/' + MAX_INIT_RETRIES + '):');\n console.log(' instantsearch.js:', instantsearchLoaded ? '✅ 已加载' : '❌ 未加载');\n console.log(' TypesenseAdapter:', adapterLoaded ? '✅ 已加载' : '❌ 未加载');\n \n if (!instantsearchLoaded || !adapterLoaded) {\n initRetryCount++;\n \n if (initRetryCount >= MAX_INIT_RETRIES) {\n console.error('');\n console.error('❌ Typesense 依赖库加载失败!');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('');\n console.error('🔧 请检查 _config.butterfly.yml 配置:');\n console.error('');\n console.error('inject:');\n console.error(' bottom: # ⚠️ 使用 bottom 而不是 head');\n console.error(' - ');\n console.error(' - ');\n console.error(' - ');\n console.error('');\n console.error('💡 或在控制台手动检查:');\n console.error(' typeof instantsearch');\n console.error(' typeof TypesenseInstantSearchAdapter');\n console.error('');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n \n showErrorMessage();\n return;\n }\n \n console.warn('⏳ 100ms 后重试...');\n setTimeout(initTypesense, 100);\n return;\n }\n \n initRetryCount = 0;\n console.log('🚀 开始初始化 Typesense...');\n\n try {\n const typesenseAdapter = new TypesenseInstantSearchAdapter({\n server: {\n apiKey: CONFIG.apiKey,\n nodes: [{\n host: CONFIG.server.host,\n port: CONFIG.server.port,\n protocol: CONFIG.server.protocol\n }],\n cacheSearchResultsForSeconds: 120\n },\n additionalSearchParameters: CONFIG.searchParams\n });\n\n searchInstance = instantsearch({\n searchClient: typesenseAdapter.searchClient,\n indexName: CONFIG.indexName,\n routing: false\n });\n\n searchInstance.addWidgets([\n instantsearch.widgets.searchBox({\n container: '#searchbox',\n placeholder: '输入关键词寻找故事...',\n autofocus: true,\n showReset: true,\n showSubmit: false,\n showLoadingIndicator: true\n }),\n instantsearch.widgets.stats({\n container: '#stats',\n templates: {\n text: function(data) {\n if (!data.query) return '';\n return '找到 ' + data.nbHits + ' 条结果 (' + data.processingTimeMS + 'ms)';\n }\n }\n }),\n instantsearch.widgets.hits({\n container: '#hits',\n templates: {\n empty: function(results) {\n return '
' +\n '
' +\n '
找不到与 \"' + results.query + '\" 相关的内容
' +\n '
试试其他关键词吧 (´·ω·`)
' +\n '
';\n },\n item: function(hit) {\n // 使用 _highlightResult 获取高亮文本\n var titleHighlight = hit._highlightResult && hit._highlightResult.title \n ? hit._highlightResult.title.value \n : (hit.title || '');\n \n var contentHighlight = hit._highlightResult && hit._highlightResult.content \n ? hit._highlightResult.content.value \n : (hit.content || '');\n \n // 截取内容长度\n if (contentHighlight.length > 200) {\n contentHighlight = contentHighlight.substring(0, 200) + '...';\n }\n \n return '' +\n '
' + titleHighlight + '
' +\n '
' + contentHighlight + '
' +\n '
';\n }\n }\n }),\n instantsearch.widgets.pagination({\n container: '#pagination',\n padding: 2,\n showFirst: false,\n showLast: false\n })\n ]);\n\n searchInstance.start();\n isInitialized = true;\n \n console.log('✅ Typesense 初始化成功!');\n\n searchInstance.on('render', function() {\n if (isSearchOpen) {\n const input = document.querySelector('.ais-SearchBox-input');\n if (input && document.activeElement !== input) {\n input.focus();\n }\n }\n });\n\n } catch (error) {\n console.error('❌ 初始化失败:', error);\n showErrorMessage();\n }\n }\n\n // ============================================================================\n // 初始化\n // ============================================================================\n function init() {\n console.log('🔍 Typesense 搜索已准备就绪');\n console.log('💡 快捷键: Ctrl/Cmd + K');\n }\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', init);\n } else {\n init();\n }\n\n // ============================================================================\n // 全局接口\n // ============================================================================\n window.TypesenseSearch = {\n open: openSearch,\n close: closeSearch,\n isOpen: function() { return isSearchOpen; },\n getInstance: function() { return searchInstance; }\n };\n\n})();\n```\n\n# 注意\n\n{% note red %}\nindexName: \"blogs\" 和 collectionName: 'posts' 要一致!!!\n{% endnote %}"}