Node.js ElasticSearch 全文检索
ElasticSearch 是基于 Lucene 的分布式搜索引擎,用于全文搜索、日志分析、数据可视化。
核心概念
| ES 概念 | 对应关系型数据库 | 说明 |
|---|---|---|
| Index | Database | 索引(数据库) |
| Type | Table(已废弃) | ES 7+ 一个 Index 只有一个 Type |
| Document | Row | 文档(一行记录) |
| Field | Column | 字段 |
| Mapping | Schema | 字段类型定义 |
安装
bash
npm install @elastic/elasticsearch连接 + 基本操作
js
import { Client } from '@elastic/elasticsearch'
const client = new Client({ node: 'http://localhost:9200' })
// 创建索引
await client.indices.create({ index: 'articles' })
// 添加文档
await client.index({
index: 'articles',
id: '1',
document: { title: 'Node.js 教程', content: 'Node.js 是一个基于 V8 的运行时...', author: '小满' }
})
// 搜索文档
const result = await client.search({
index: 'articles',
query: { match: { title: 'Node.js' } }
})
console.log(result.hits.hits) // 匹配结果
// 模糊搜索
await client.search({
query: { fuzzy: { title: 'Nod.js' } } // 容忍拼写错误
})
// 高亮结果
await client.search({
query: { match: { content: 'V8' } },
highlight: { fields: { content: {} } }
})应用场景
| 场景 | 说明 |
|---|---|
| 全文搜索 | 商品搜索、文章搜索 |
| 日志分析 | ELK(Elasticsearch + Logstash + Kibana) |
| 数据分析 | 聚合统计、实时看板 |
| 自动补全 | suggest 搜索建议 |