性能优化
1
写入性能优化
提升索引写入速度的配置和方法
# 批量写入(Bulk API)
POST /_bulk
{ "index": { "_index": "my_index", "_id": "1" } }
{ "field": "value1" }
{ "index": { "_index": "my_index", "_id": "2" } }
{ "field": "value2" }
# 索引优化设置
PUT /my_index/_settings
{
"index": {
"refresh_interval": "-1", # 禁用刷新
"number_of_replicas": 0, # 减少副本
"translog.durability": "async", # 异步translog
"translog.sync_interval": "60s"
}
}
# 写入完成后恢复设置
PUT /my_index/_settings
{
"index": {
"refresh_interval": "1s",
"number_of_replicas": 1
}
}
写入优化建议
- 使用Bulk API批量写入,每批5-15MB
- 大批量导入时临时禁用刷新和副本
- 使用多线程并发写入
- 避免频繁更新同一条文档
- 使用自动生成ID(比指定ID快)
2
搜索性能优化
# 使用filter替代must(不计算评分,可缓存)
{
"query": {
"bool": {
"must": [
{ "match": { "title": "elasticsearch" } }
],
"filter": [
{ "term": { "status": "published" } },
{ "range": { "date": { "gte": "2024-01-01" } } }
]
}
}
}
# 限制返回字段
{
"_source": ["title", "author", "date"],
"query": {
"match": { "title": "search" }
}
}
# 使用scroll进行深度分页
POST /my_index/_search?scroll=1m
{
"size": 100,
"query": {
"match_all": {}
}
}
# 使用search_after进行实时分页
{
"size": 10,
"query": {
"match_all": {}
},
"sort": [
{ "date": "desc" },
{ "_id": "desc" }
],
"search_after": [1640995200000, "doc_id"]
}
3
内存优化
# JVM配置优化(jvm.options) # 堆内存设置(不超过32GB) -Xms16g -Xmx16g # 禁用交换内存 bootstrap.memory_lock: true # 索引缓冲区大小(默认10%) indices.memory.index_buffer_size: 20% # 字段数据缓存限制 indices.fielddata.cache.size: 30% # 查询缓存 index.queries.cache.enabled: true # 请求缓存 index.requests.cache.enable: true
内存注意事项
- 堆内存不要超过物理内存的50%
- 堆内存不要超过32GB(压缩指针优化)
- 预留足够内存给文件系统缓存
- 监控堆使用率和GC频率
4
分片与副本优化
# 合理设置分片数
PUT /my_index
{
"settings": {
"number_of_shards": 5, # 根据数据量设置
"number_of_replicas": 1 # 生产环境至少1个副本
}
}
# 分片分配策略
cluster.routing.allocation.same_shard.host: true
cluster.routing.allocation.awareness.attributes: rack_id
# 分片平衡设置
cluster.routing.rebalance.enable: all
cluster.routing.allocation.allow_rebalance: indices_all_active
# 强制合并段(优化只读索引)
POST /my_index/_forcemerge?max_num_segments=1
5
监控与诊断
# 慢查询日志配置
PUT /_cluster/settings
{
"transient": {
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.indexing.slowlog.threshold.index.warn": "10s"
}
}
# 查看热点线程
GET /_nodes/hot_threads
# 查看节点统计
GET /_nodes/stats
# 查看索引统计
GET /my_index/_stats
# 任务监控
GET /_tasks?detailed=true&actions=*search*
# 取消任务
POST /_tasks/task_id/_cancel