當我們使用ES批量插入數據的時候,一般會這樣寫代碼:
from elasticsearch import Elasticsearch,helpers es =Elasticsearch(hosts=[{'host':'localhost','port':9200}]) def gendata(): mywords =['foo','bar','baz'] for word in mywords: yield {"_index":"mywords","_type":"document","_type":"document","doc":{"word": word}} helpersbulk(es,gendata())
但當ES的負荷過大時,這種寫法可能會拋出連接超時的異常。
為了解決這個問題,在初始化ES連接對象時,可以設置一個更大的超時時間:
es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}], timeout=60)
但有時候,即時設置為60秒還是有可能遇到超時異常,但這個超時時間並非越大越好,所以最好能夠讓ES在遇到超時的情況下自動重試。
在創建ES連接對象時,還可以再加兩個參數,實現超時自動重試3次:
es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}], timeout=60, max_retries=3, retry_on_timeout=True)
通過添加 max_retries
和 retry_on_timeout
兩個參數,就能實現超時自動重試了。
如果你直接看ES的文檔,你可能會找不到這兩個參數,如下圖所示。
這並非是ES的文檔有問題,而是因為這兩個參數隱藏在 **kwargs
里面,如下圖所示。
點進 Transport
就可以看到這兩個參數: