引言

ES集群优化对于大规模应用至关重要。本文介绍ES集群优化的实践经验。

一、集群架构

1.1 节点类型

1
2
3
4
5
6
7
8
9
10
11
# Master节点
node.master: true
node.data: false

# Data节点
node.master: false
node.data: true

# Coordinating节点
node.master: false
node.data: false

1.2 分片设计

1
2
3
4
5
6
7
8
9
10
# 分片数 = 数据量(GB) / 30GB
# 副本数 = 1-2(根据可用性要求)

PUT /products
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}

二、性能优化

2.1 批量操作

1
2
3
4
5
6
# 使用bulk API
POST /_bulk
{"index":{"_index":"products"}}
{"name":"Product 1","price":100}
{"index":{"_index":"products"}}
{"name":"Product 2","price":200}

2.2 禁用_source

1
2
3
4
5
6
7
8
9
# 减少存储空间
PUT /products
{
"mappings": {
"_source": {
"enabled": false
}
}
}

2.3 使用filter代替query

1
2
3
4
5
6
7
8
9
10
11
# filter有缓存,性能更好
GET /products/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "status": "active" } }
]
}
}
}

三、监控与运维

3.1 集群健康

1
2
3
4
5
6
7
8
# 查看集群健康
GET /_cluster/health

# 查看节点状态
GET /_cat/nodes?v

# 查看分片分布
GET /_cat/shards?v

3.2 性能指标

1
2
3
4
5
# 查看索引统计
GET /_stats

# 查看慢查询
GET /_nodes/stats/indices/search

四、常见问题

4.1 集群变黄/红

  • 检查分片分配
  • 增加节点
  • 调整副本数

4.2 查询慢

  • 优化查询语句
  • 添加过滤条件
  • 使用routing

总结

ES集群优化要点:

  1. 合理架构:分离Master和Data节点
  2. 分片设计:合适的分片数和副本数
  3. 性能优化:批量操作、使用filter
  4. 监控运维:实时监控集群状态

参考资料