Elasticsearch 是全球最流行的分布式搜索引擎,基于 Lucene 构建,提供近实时搜索、聚合分析与全文检索能力。
1. 核心概念
| 概念 | 类比 RDBMS | 说明 |
|---|---|---|
| Index | Database | 索引,逻辑命名空间 |
| Type | Table | 7.x 已废弃,8.x 移除 |
| Document | Row | 一条 JSON 记录 |
| Field | Column | 字段 |
| Mapping | Schema | 字段类型定义 |
| Shard | Partition | 分片 |
| Replica | Replica | 副本 |
2. 倒排索引
文档:
Doc1: "Elasticsearch is a search engine"
Doc2: "Lucene is the core of Elasticsearch"
倒排索引:
"elasticsearch" → [Doc1, Doc2]
"search" → [Doc1]
"engine" → [Doc1]
"lucene" → [Doc2]
"core" → [Doc2]
ES 还存储:
- Term Frequency (TF):词在文档中出现次数
- Document Frequency (DF):包含该词的文档数
- Norms:字段长度归一化因子
- Positions:词在文档中的位置(用于短语查询)
- Offsets:字符偏移(用于高亮)
3. 分词与分析器
// 自定义 IK 分词器 + 拼音过滤器
PUT /products
{
"settings": {
"analysis": {
"analyzer": {
"ik_pinyin": {
"tokenizer": "ik_max_word",
"filter": ["pinyin_filter"]
}
},
"filter": {
"pinyin_filter": {
"type": "pinyin",
"keep_separate_first_letter": false,
"keep_full_pinyin": true,
"keep_original": true
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"price": { "type": "float" },
"category": { "type": "keyword" },
"tags": { "type": "keyword" },
"create_time": { "type": "date" }
}
}
}
4. 查询 DSL
// Bool 复合查询
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "multi_match": {
"query": "手机",
"fields": ["title^3", "description"]
}}
],
"filter": [
{ "range": { "price": { "gte": 1000, "lte": 5000 } }},
{ "term": { "category": "电子产品" }}
]
}
},
"sort": [
{ "_score": "desc" },
{ "sales": "desc" }
],
"from": 0,
"size": 20,
"highlight": {
"fields": {
"title": { "pre_tags": ["<em>"], "post_tags": ["</em>"] }
}
},
"aggs": {
"by_category": {
"terms": { "field": "category" }
},
"price_stats": {
"stats": { "field": "price" }
}
}
}
5. 集群架构
Node 类型:
- Master: 管理集群状态(3 个候选)
- Data: 存储数据和执行查询
- Ingest: 预处理文档(Pipeline)
- Coordinating: 仅路由请求(大集群专用)
- ML: 机器学习节点
5.1 分片规划
# 黄金法则
# 分片大小: 10-50GB
# 分片数/节点: < 20
# 堆内存: ≤ 30GB(压缩指针优化)
# 总分片数 ≈ 数据量(GB) / 30
# 创建索引时指定
PUT /logs-2024-01
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1,
"refresh_interval": "30s"
}
}
5.2 ILM (Index Lifecycle Management)
PUT _ilm/policy/logs_policy
{
"policy": {
"phases": {
"hot": {
"actions": {
"rollover": {
"max_size": "50GB",
"max_age": "30d"
}
}
},
"warm": {
"min_age": "7d",
"actions": {
"shrink": { "number_of_shards": 1 },
"forcemerge": { "max_num_segments": 1 }
}
},
"cold": {
"min_age": "30d",
"actions": {
"allocate": { "require": { "data": "cold" }},
"freeze": {}
}
},
"delete": {
"min_age": "90d"
}
}
}
}
6. 性能优化
| 优化点 | 方法 |
|---|---|
| 写入吞吐 | 批量写入 (bulk)、增大 refresh_interval、使用 _bulk |
| 查询性能 | 使用 filter(缓存)、避免深分页 (search_after)、预加载 fielddata |
| 存储 | 禁用 _all、使用 _source filtering、force merge |
| 集群 | 专用协调节点、跨集群复制、冷热分离 |
总结
- 分词:中文用 IK,搜索用 ik_smart,索引用 ik_max_word
- Mapping:能用 keyword 不用 text(聚合、排序、过滤)
- 查询:must + filter 分离,filter 走缓存
- 集群:Master 和数据节点分离,监控分片分布
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。