學習筆記:Elasticsearch 文檔檢索系統
1. 技術棧與核心組件
- Node.js:后端運行環境,適合構建高性能 Web 服務。
- Express:Node.js 的 Web 框架,簡化 API 開發。
- Elasticsearch:分布式全文檢索引擎,支持高效的文本檢索。
- 原生 HTML+JS:前端頁面實現,便于快速演示和交互。
2. 后端實現要點
-
API 設計
/import
:導入本地 JSON 文檔到 Elasticsearch,支持批量操作。/search
:根據關鍵詞檢索文檔,支持多字段(標題、內容)全文檢索。
-
Elasticsearch 客戶端
- 使用
@elastic/elasticsearch
npm 包連接本地 ES 服務。 - 索引管理:每次導入前先刪除舊索引,保證數據一致性。
- 字段映射(Mapping):定義文檔結構,指定哪些字段可檢索。
- 使用
-
批量導入
- 通過
bulk
API 一次性導入多條文檔,提升效率。
- 通過
-
CORS 跨域
- 使用
cors
中間件,允許前端頁面直接訪問后端 API。
- 使用
// =========================
// 導入文檔到 Elasticsearch
// =========================
app.post('/import', async (req, res) => {try {// 1. 檢查索引是否存在,存在則先刪除(保證每次導入都是全新數據)const exists = await esClient.indices.exists({ index: esIndex });// exists.body 為 true 表示索引存在,需先刪除if (exists.body) {await esClient.indices.delete({ index: esIndex });}// 2. 創建新索引,并定義字段映射await esClient.indices.create({index: esIndex,body: {mappings: {properties: {id: { type: 'integer' }, // 文檔IDtitle: { type: 'text' }, // 標題,全文檢索content: { type: 'text' } // 內容,全文檢索}}}});// 3. 讀取本地 docs.json 文件,獲取10篇文檔const docs = JSON.parse(fs.readFileSync(path.join(__dirname, 'docs.json'), 'utf-8'));// 4. 構造批量導入 bodyconst body = docs.flatMap(doc => [{ index: { _index: esIndex, _id: doc.id } }, doc]);// 5. 批量導入文檔到 ESawait esClient.bulk({ refresh: true, body });res.json({ success: true, message: '導入成功', count: docs.length });} catch (err) {// 錯誤處理res.status(500).json({ success: false, error: err.message });}
});// =========================
// 查詢接口:根據關鍵詞檢索文檔
// =========================
app.get('/search', async (req, res) => {const q = req.query.q || ''; // 獲取查詢參數try {// 調用 ES 的 search API,multi_match 支持多個字段全文檢索const result = await esClient.search({index: esIndex,body: {query: {multi_match: {query: q,fields: ['title', 'content'] // 在標題和內容中查找}}}});// 取出命中結果,提取需要的字段const hits = result.hits.hits.map(hit => ({id: hit._source.id,title: hit._source.title,content: hit._source.content,score: hit._score // 相關性分數}));res.json({ success: true, data: hits });} catch (err) {// 錯誤處理res.status(500).json({ success: false, error: err.message });}
});
3. 前端實現要點
-
頁面結構
- 搜索輸入框 + 按鈕,用戶輸入關鍵詞后觸發檢索。
- 結果區域動態渲染檢索到的文檔列表。
-
與后端交互
- 使用
fetch
發送 GET 請求到/search
,獲取 JSON 格式結果。 - 處理異常和無結果情況,提升用戶體驗。
- 使用
-
界面美化
- CSS 實現響應式布局和美觀樣式,適配不同屏幕。
- CSS 實現響應式布局和美觀樣式,適配不同屏幕。
4. 數據結構與流程
-
文檔結構
- 每條文檔包含
id
、title
、content
字段。 - 示例數據存儲于
backend/docs.json
。
- 每條文檔包含
-
檢索流程
- 用戶輸入關鍵詞,點擊搜索。
- 前端調用后端
/search
接口。 - 后端在 ES 中檢索,返回相關文檔及分數。
- 前端展示檢索結果。
5. 常見問題與調試
- Elasticsearch 未啟動:后端無法連接 ES,需先啟動本地 ES 服務。
- 端口沖突:確保 3001 端口未被占用。
- 跨域問題:已通過 CORS 解決,前后端可分開運行。