🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Shard request cache(分片请求缓存) 原文链接 : [https://www.elastic.co/guide/en/elasticsearch/reference/5.3/shard-request-cache.html](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/shard-request-cache.html) 译文链接 : [Shard request cache(分片请求缓存)](/pages/viewpage.action?pageId=9406785) 贡献者 : [赵芳城](/display/~zhaofangcheng) 当搜索的请求运行在单个或者多个索引上时,每个涉及的分片在本地执行搜索并将其本地结果返回给协调节点,该协调节点将这些分片级结果合并为“全局”结果集。 分片级请求缓存模块将本地结果缓存在每个分片上。 这允许经常使用(并且可能很重)的搜索请求几乎立即返回结果。 请求缓存非常适合日志记录用例,其中只有最近的索引正在被更新 - 较旧索引的结果将直接从缓存提供。 默认情况下,request cache(请求缓存)只会缓存size =0(结果为空)的的请求,它并不会缓存命中结果,但是他会缓存命中总数, [aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-aggregations.html), and [suggestions](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/search-suggesters.html). 大多数现在用到的查询都不会缓存 (请参考 “[Date Mathedit](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/common-options.html#date-math)”章节) . ## cache invalidation(缓存失效) 缓存的机制是智能,他保证了及时未被缓存的索引也能在被接近实时(NRT)的搜索出来。 当分片中的数据确实已经发生改变的情况下, 缓存结果才会根据分片的刷新自动失效。换言之, 当你请求未被缓存的索引时,总会得到相同的结果。 越长时间的刷新间隔,则缓存就被越长时间的保留,当缓存满了,最近未被使用的缓存将被驱除 缓存可以通过[`clear-cache` API](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/indices-clearcache.html "Clear Cache")来配置过期时间: ``` POST /kimchy,elasticsearch/_cache/clear?request_cache=true ``` ## Enabling and disabling caching(启用和停用缓存) 缓存默认是启用状态,你可以在创建索引的时候通过以下方式停用缓存: ``` PUT /my_index { "settings": { "index.requests.cache.enable": false } } ``` 缓存也可以通过 [`update-settings`](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/indices-update-settings.html "Update Indices Settings") API,动态的对已有的缓存进行启用和停用: ``` PUT /my_index/_settings { "index.requests.cache.enable": true } ``` ## Enabling and disabling caching per request(每个请求的缓存启用和停用) 可以在请求时通过请求参数`request_cache`来为每个请求启动和关闭缓存,如果是用了此参数,他将会覆盖index-level配置: ``` GET /my_index/_search?request_cache=true { "size": 0, "aggs": { "popular_colors": { "terms": { "field": "colors" } } } } ``` 注意 如果您的查询使用脚本,其结果是不确定的(例如,它使用一个随机函数或引用当前的时间)你需要将request_cache设置为false,来禁用该请求的缓存 请求size大于0 的时候不会缓存,即使request cache已经设置为启用。你可以在请求中详细列的出来参数来缓存你的请求。 ## Cache key(缓存key) JSON整体被用作缓存key。这就意味着如果JSON发生变化 例如,如果key的排序发生了变化 - 那么缓存key将不被认可。 提示 大多数JSON库都支持规范模式,以确保JSON密钥始终以相同的顺序排列。 该规范模式可以在应用程序中使用,以确保请求始终以相同的方式序列化。 ## Cache settings(缓存配置) 缓存在节点级别进行管理,并且默认最大大小为heap(堆)的1%。 在config / elasticsearch.yml文件中更改: ``` indices.requests.cache.size: 2% ``` 此外,您可以使用indices.requests.cache.expire设置为缓存有效时间,这样做多此一举。 因为当索引被刷新时,老旧的结果将自动失效,此设置仅供参考。 ## Monitoring cache usage(监控缓存使用)  缓存大小和缓存被驱逐次数可以通过索引查看, 缓存的大小单位: bytes(字节)`[indices-stats](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/indices-stats.html "Indices Stats") `API:  ``` GET /_stats/request_cache?human ```  node(节点)与`[nodes-stats](https://www.elastic.co/guide/en/elasticsearch/reference/5.3/cluster-nodes-stats.html "Nodes Stats") `API:  ``` GET /_nodes/stats/indices/request_cache?human ```