1 line
24 KiB
JSON
1 line
24 KiB
JSON
{"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 - <script src=\"https://cdn.jsdmirror.com/npm/instantsearch.js@4.56.0\"></script>\n - <script src=\"https://cdn.jsdmirror.com/npm/typesense-instantsearch-adapter@2.7.0/dist/typesense-instantsearch-adapter.min.js\"></script>\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 '<div class=\"ts-empty\">' +\n '<div style=\"color: #f44336;\"><i class=\"fas fa-exclamation-triangle\" style=\"font-size: 3rem;\"></i></div>' +\n '<div style=\"font-size: 1.1rem; font-weight: bold; margin: 15px 0;\">搜索服务加载失败</div>' +\n '<div style=\"font-size: 0.9rem; color: #666; line-height: 1.8;\">' +\n '<p>依赖库未能正确加载,请检查以下配置:</p>' +\n '<ol style=\"text-align: left; max-width: 500px; margin: 15px auto;\">' +\n '<li>确认已在 <code>_config.butterfly.yml</code> 中正确引入依赖</li>' +\n '<li>检查 JS 文件加载顺序(先 instantsearch.js,再 adapter)</li>' +\n '<li>尝试更换 CDN 或使用本地文件</li>' +\n '<li>打开浏览器控制台查看详细错误信息</li>' +\n '</ol>' +\n '</div>' +\n '<div style=\"margin-top: 20px;\">' +\n '<button onclick=\"location.reload()\" style=\"padding: 10px 20px; background: #49b1f5; color: white; border: none; border-radius: 5px; cursor: pointer;\">重新加载页面</button>' +\n '</div>' +\n '</div>';\n }\n\n // ============================================================================\n // 1. 动态插入 HTML 结构\n // ============================================================================\n const searchHTML = `\n <div id=\"typesense-search-mask\" class=\"ts-mask\" style=\"display:none;\">\n <div id=\"typesense-search-container\" class=\"ts-container\">\n <div class=\"ts-header\">\n <span class=\"ts-title\">\n <i class=\"fas fa-search\"></i> 本站搜索\n </span>\n <span id=\"close-typesense\" class=\"ts-close\" aria-label=\"关闭搜索\">×</span>\n </div>\n <div id=\"searchbox\"></div>\n <div id=\"stats\" class=\"ts-stats\"></div>\n <div id=\"hits\" class=\"ts-hits\"></div>\n <div id=\"pagination\" class=\"ts-pagination\"></div>\n <div class=\"ts-footer\">\n <small>Search powered by <strong>Typesense</strong></small>\n </div>\n </div>\n </div>\n\n <style>\n .ts-mask {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.7);\n z-index: 10000;\n backdrop-filter: blur(5px);\n -webkit-backdrop-filter: blur(5px);\n opacity: 0;\n transition: opacity 300ms ease;\n }\n .ts-mask.active { opacity: 1; }\n .ts-container {\n margin: 5% auto;\n width: 90%;\n max-width: 650px;\n background: var(--search-bg, var(--card-bg, #fff));\n padding: 25px;\n border-radius: 12px;\n box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);\n position: relative;\n z-index: 10001;\n transform: translateY(-50px);\n opacity: 0;\n transition: all 300ms ease;\n }\n .ts-mask.active .ts-container {\n transform: translateY(0);\n opacity: 1;\n }\n .ts-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 20px;\n border-bottom: 2px solid var(--text-highlight-color, #49b1f5);\n padding-bottom: 10px;\n }\n .ts-title {\n font-size: 1.2rem;\n font-weight: bold;\n color: var(--text-highlight-color, #49b1f5);\n }\n .ts-close {\n cursor: pointer;\n font-size: 28px;\n color: var(--font-color, #333);\n line-height: 1;\n transition: color 0.2s, transform 0.2s;\n }\n .ts-close:hover {\n color: var(--text-highlight-color, #49b1f5);\n transform: scale(1.1);\n }\n .ais-SearchBox-input {\n position: relative;\n z-index: 10002;\n cursor: text;\n padding: 12px 40px 12px 15px !important;\n border-radius: 8px !important;\n border: 2px solid #eee !important;\n width: 100%;\n outline: none;\n transition: border-color 0.3s, box-shadow 0.3s;\n background: var(--card-bg, #fff);\n color: var(--font-color, #333);\n font-size: 1rem;\n }\n .ais-SearchBox-input:focus {\n border-color: var(--text-highlight-color, #49b1f5) !important;\n box-shadow: 0 0 0 3px rgba(73, 177, 245, 0.1);\n }\n .ts-stats {\n margin: 10px 0;\n font-size: 0.85rem;\n color: var(--font-color, #666);\n opacity: 0.8;\n }\n .ts-hits {\n max-height: 55vh;\n overflow-y: auto;\n margin-top: 15px;\n padding-right: 5px;\n }\n .ts-hits::-webkit-scrollbar { width: 6px; }\n .ts-hits::-webkit-scrollbar-track {\n background: var(--card-bg, #f1f1f1);\n border-radius: 10px;\n }\n .ts-hits::-webkit-scrollbar-thumb {\n background: var(--text-highlight-color, #49b1f5);\n border-radius: 10px;\n }\n .ts-empty {\n text-align: center;\n padding: 40px 20px;\n color: var(--font-color, #999);\n }\n .ts-empty i {\n font-size: 3rem;\n margin-bottom: 15px;\n opacity: 0.3;\n }\n .ts-empty code {\n background: #f5f5f5;\n padding: 2px 6px;\n border-radius: 3px;\n font-family: monospace;\n color: #e91e63;\n }\n .ts-empty ol {\n padding-left: 20px;\n }\n .ts-empty li {\n margin: 8px 0;\n }\n .ts-result-item {\n border-radius: 8px;\n transition: all 0.2s ease;\n margin-bottom: 10px;\n padding: 15px;\n border: 1px solid transparent;\n text-decoration: none;\n display: block;\n background: var(--card-bg, #fff);\n }\n .ts-result-item:hover {\n background: var(--text-bg-hover, rgba(73, 177, 245, 0.05));\n border-color: var(--text-highlight-color, #49b1f5);\n transform: translateX(5px);\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n }\n .ts-result-title {\n font-weight: bold;\n color: var(--text-highlight-color, #49b1f5);\n font-size: 1.1rem;\n margin-bottom: 8px;\n display: block;\n line-height: 1.4;\n }\n .ts-result-content {\n font-size: 0.9rem;\n color: var(--font-color, #666);\n line-height: 1.6;\n opacity: 0.85;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n }\n .ts-result-item mark {\n background: #ffeb3b;\n color: #000;\n padding: 2px 4px;\n border-radius: 3px;\n font-weight: 500;\n }\n .ts-pagination {\n margin-top: 20px;\n display: flex;\n justify-content: center;\n gap: 5px;\n }\n .ais-Pagination-list {\n display: flex;\n list-style: none;\n padding: 0;\n margin: 0;\n gap: 5px;\n }\n .ais-Pagination-link {\n display: block;\n padding: 8px 12px;\n border: 1px solid #ddd;\n border-radius: 5px;\n color: var(--font-color, #333);\n text-decoration: none;\n transition: all 0.2s;\n background: var(--card-bg, #fff);\n }\n .ais-Pagination-link:hover {\n background: var(--text-highlight-color, #49b1f5);\n color: #fff;\n }\n .ais-Pagination-item--selected .ais-Pagination-link {\n background: var(--text-highlight-color, #49b1f5);\n color: #fff;\n }\n .ts-footer {\n text-align: right;\n margin-top: 15px;\n border-top: 1px solid var(--border-color, #eee);\n padding-top: 10px;\n }\n @media (max-width: 768px) {\n .ts-container {\n margin: 10px;\n width: calc(100% - 20px);\n padding: 20px 15px;\n }\n .ts-hits { max-height: 50vh; }\n }\n [data-theme=\"dark\"] .ts-mask,\n .dark-mode .ts-mask {\n background: rgba(0, 0, 0, 0.85);\n }\n </style>\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(' - <script src=\"https://cdn.jsdelivr.net/npm/instantsearch.js@4.56.0\"></script>');\n console.error(' - <script src=\"https://cdn.jsdelivr.net/npm/typesense-instantsearch-adapter@2.7.0/dist/typesense-instantsearch-adapter.min.js\"></script>');\n console.error(' - <script src=\"/js/typesense-search-fixed.js\"></script>');\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 '找到 <strong>' + data.nbHits + '</strong> 条结果 (' + data.processingTimeMS + 'ms)';\n }\n }\n }),\n instantsearch.widgets.hits({\n container: '#hits',\n templates: {\n empty: function(results) {\n return '<div class=\"ts-empty\">' +\n '<div><i class=\"fas fa-search\"></i></div>' +\n '<div>找不到与 \"<strong>' + results.query + '</strong>\" 相关的内容</div>' +\n '<div style=\"margin-top: 10px;\">试试其他关键词吧 (´·ω·`)</div>' +\n '</div>';\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 '<a href=\"' + hit.url + '\" class=\"ts-result-item\">' +\n '<div class=\"ts-result-title\">' + titleHighlight + '</div>' +\n '<div class=\"ts-result-content\">' + contentHighlight + '</div>' +\n '</a>';\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 %}"} |