Skip to content

Node.js ElasticSearch 全文检索

ElasticSearch 是基于 Lucene 的分布式搜索引擎,用于全文搜索、日志分析、数据可视化。

核心概念

ES 概念对应关系型数据库说明
IndexDatabase索引(数据库)
TypeTable(已废弃)ES 7+ 一个 Index 只有一个 Type
DocumentRow文档(一行记录)
FieldColumn字段
MappingSchema字段类型定义

安装

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 搜索建议