給ElasticSearch引擎配置慢查詢日志,可以實時監控搜索過慢的日志。雖然ElasticSearch以快速搜索而出名,但隨着數據量的進一步增大或是服務器的一些性能問題,會有可能出現慢查詢的情況。慢查詢日志可以幫助你快速定位到是什么 Index 和 語句 過慢。甚至還可以用Opster Search Log Analyzer分析你的慢查詢日志,Opster Search Log Analyzer還會針對你的慢查詢日志提供專門的優化建議。
默認情況下,慢查詢日志打印功能是關閉的。你可以通過設置查詢的threshold值來設置,通過如下的命令查看當前設置的值。下面以mytask索引為例:
curl -XGET "http://<your elastic host>:9200/mytask/_settings"
上面查詢了mytask當前設置的值,如果你想輸出所有索引的設置信息,那么只需要將mytask改為_all就可以了 /_all/_settings .
如果輸出的信息中,如果沒有threadhold值那么就還沒有進行設置。需要分別設置 搜索部分 和 索引部分 兩部分。
搜索部分
curl -XPUT "http://<your elastic host>:9200/mytask/_settings" -H 'Content-Type: application/json' -d'
{
"index.search.slowlog.threshold.query.warn": "10s",
"index.search.slowlog.threshold.query.info": "5s",
"index.search.slowlog.threshold.query.debug": "2s",
"index.search.slowlog.threshold.query.trace": "500ms",
"index.search.slowlog.threshold.fetch.warn": "1s",
"index.search.slowlog.threshold.fetch.info": "800ms",
"index.search.slowlog.threshold.fetch.debug": "500ms",
"index.search.slowlog.threshold.fetch.trace": "200ms",
"index.search.slowlog.level": "info"
}'
上面給Elastic Search搜索(Search)設置了慢查詢日志輸出分界線為info級。上面有設置query和fetch兩部分,query表示獲取文檔(Documents)的時間,fetch表示獲取實際數據源(Source)的時間。
索引部分
curl -XPUT "http://<your elastic host>:9200/mytask/_settings" -H 'Content-Type: application/json' -d'
{
"index.indexing.slowlog.threshold.index.warn": "10s",
"index.indexing.slowlog.threshold.index.info": "5s",
"index.indexing.slowlog.threshold.index.debug": "2s",
"index.indexing.slowlog.threshold.index.trace": "500ms",
"index.indexing.slowlog.level": "info",
"index.indexing.slowlog.source": "1000"
}'
上面給Elastic Search索引(Indexing)設置了慢查詢日志輸出的分界線為info級,並且每條數據最多輸出源數據(Source)的前1000個字符。
然后你可以再通過命令 mytask/_settings 來檢查設置是否生效。如果設置沒有問題了,那么你接下來就可以在日志目錄中觀察到你的慢日志文件了。
獲取日志輸出目錄
curl -XGET "http://<your elatic host>:9200/_nodes/settings?pretty=true"
在settings.path.logs下找到打印日志的目錄。默認情況,慢日志文件名格式為:
<cluster_name>_index_search_slowlog.log <cluster_name>_index_indexing_slowlog.log
由於ElasticSearch的處理速度非常的快,所以很有可能沒有慢查詢的日志。你可以通過如下的操作,將所有的查詢和索引都記錄到日志中。
curl -XPUT "http://<your elatic host>:9200/task/_settings" -H 'Content-Type: application/json' -d'
{
"index.search.slowlog.threshold.query.trace": "0ms",
"index.search.slowlog.threshold.fetch.trace": "0ms",
"index.search.slowlog.level": "trace",
"index.indexing.slowlog.threshold.index.trace": "0ms",
"index.indexing.slowlog.level": "trace"
}'
上面將打印日志的級別設置為trace, 並且將trace的相應的時間設置為0ms,這樣就會打印所有的操作記錄了。注意:這樣的設置僅用於測試!
上面都是以mytask索引為例展示數據的索引,你也可以將mytask替換為其他索引名稱,或者使用_all給所有索引設置慢查詢日志(不建議這樣設置).
慢查詢日志 對於ElasticSearch引擎的性能 非常地重要,同時也能給你的系統提供一層監控,以便你及時優化出現的慢查詢。 通常情況下,可能會偶爾出現慢查詢的語句,這種情況無需要做針對性的處理(有可能是垃圾回收或CPU緊張等造成的暫時現象)。但如果出現大片幅度的慢查詢日志記錄,就需要進行針對性的優化。