Skip to content

缓存与内存管理

缓存类型

1. Node Query Cache

json
// 每个节点一个,由所有shard共享
GET /_nodes/stats/indices/query_cache
配置说明
indices.queries.cache.size缓存大小,默认10%

2. Shard Request Cache

json
// 每个shard的查询缓存
GET /_nodes/stats/indices/request_cache
配置说明
indices.requests.cache.size缓存大小,默认1%
json
// 查询时使用request cache
GET /products/_search?request_cache=true
{
  "aggs": {"avg_price": {"avg": {"field": "price"}}}
}

3. Fielddata Cache

json
// 用于排序、聚合、脚本
GET /_nodes/stats/indices/fielddata
json
// 限制fielddata大小
{
  "indices": {
    "fielddata": {
      "limit": "40%"
    }
  }
}

4. Circuit Breaker

json
// 防止OOM
{
  "indices": {
    "breaker": {
      "total": {
        "limit": "70%"
      },
      "fielddata": {
        "limit": "40%"
      },
      "request": {
        "limit": "60%"
      }
    }
  }
}

缓存管理

查看缓存使用

bash
GET /_nodes/stats

GET /_all/stats

GET /my_index/_stats

清除缓存

json
// 清除所有缓存
POST /_cache/clear

// 清除query cache
POST /_cache/clear?query=true

// 清除request cache
POST /_cache/clear?request=true

// 清除fielddata cache
POST /my_index/_cache/clear?fielddata=true

缓存失效时机

缓存类型失效时机
Query Cachesegment refresh
Request Cachesegment refresh
Fielddata Cache手动清除或OOM

内存管理

JVM堆配置

yaml
# jvm.options
-Xms4g
-Xmx4g
# 建议:物理内存50%,不要超过32GB

堆外内存

yaml
# 禁用mmapfs use
index.store.type: niofs

内存监控

bash
GET /_nodes/stats

# 关键指标
# - jvm.heap.used_in_bytes
# - jvm.heap.max_in_bytes
# - fielddata.memory_size_in_bytes
# - query_cache.memory_size_in_bytes

内存问题排查

bash
# 1. 检查fielddata使用
GET /_nodes/stats/indices/fielddata?level=shards

# 2. 检查biggest segments
GET /my_index/_segments?pretty

# 3. 手动清理fielddata
POST /my_index/_cache/clear?fielddata=true

面试考点

Q: 查询缓存能用吗?

  • 不缓存带from+size的查询
  • 不缓存带script的查询
  • 不缓存带sort的查询

Q: fielddata哪来的?

  • 排序、聚合、脚本
  • 不是_source,直接加载到内存

Q: 内存占用高怎么解决?

  • 减少并发查询
  • 清理缓存
  • 调大heap(不超过32GB)
  • 降低fielddata limit

最后更新: