2016-11-18 25 views
3

我正在嘗試提高對ElasticSearch進行測試的套件的性能。ElasticSearch更新不是即時的,您如何等待ElasticSearch完成更新其索引?

測試需要很長時間,因爲Elasticsearch在更新後不立即更新索引。例如,下面的代碼運行時不會引發斷言錯誤。

from elasticsearch import Elasticsearch 
elasticsearch = Elasticsearch('es.test') 

# Asumming that this is a clean and empty elasticsearch instance 
elasticsearch.update(
    index='blog', 
    doc_type=,'blog' 
    id=1, 
    body={ 
     .... 
    } 
) 

results = elasticsearch.search() 
assert not results 
# results are not populated 

目前出黑客一起解決這個問題丟棄time.sleep呼叫到代碼,給ElasticSearch一些時間來更新它的索引。

from time import sleep 
from elasticsearch import Elasticsearch 
elasticsearch = Elasticsearch('es.test') 

# Asumming that this is a clean and empty elasticsearch instance 
elasticsearch.update(
    index='blog', 
    doc_type=,'blog' 
    id=1, 
    body={ 
     .... 
    } 
) 

# Don't want to use sleep functions 
sleep(1) 

results = elasticsearch.search() 
assert len(results) == 1 
# results are now populated 

顯然,這不是很大,因爲它是相當易出故障,假設如果ElasticSearch時間超過一秒來更新它的索引,儘管如何不太可能是,測試將失敗。當你運行這樣的100個測試時,它也非常慢。

我試圖解決這個問題一直在查詢pending cluster jobs以查看是否還有任務需要完成。然而,這不起作用,並且此代碼將運行而不會出現斷言錯誤。

from elasticsearch import Elasticsearch 
elasticsearch = Elasticsearch('es.test') 

# Asumming that this is a clean and empty elasticsearch instance 
elasticsearch.update(
    index='blog', 
    doc_type=,'blog' 
    id=1, 
    body={ 
     .... 
    } 
) 

# Query if there are any pending tasks 
while elasticsearch.cluster.pending_tasks()['tasks']: 
    pass 

results = elasticsearch.search() 
assert not results 
# results are not populated 

所以基本上,回到我原來的問題,ElasticSearch更新不 眼前,你怎麼等待ElasticSearch以完成更新它的指數?

回答

6

截至5.0.0,elasticsearch有一個選項:

?refresh=wait_for 

在索引,更新,刪除和大宗原料藥的。這樣,請求將不會收到響應,直到結果在ElasticSearch中可見。 (Yay!)

查看https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-refresh.html瞭解更多信息。

編輯:看來,這個功能已經在最新的Python elasticsearch API的一部分: https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.index

您elasticsearch.update更改爲:

elasticsearch.update(
    index='blog', 
    doc_type='blog' 
    id=1, 
    refresh='wait_for', 
    body={ 
     .... 
    } 
) 

,你不應該需要任何睡眠或輪詢。

+0

感謝。很抱歉,接受的速度很慢。 – Rollo

0

似乎爲我工作:

els.indices.refresh(index) 
els.cluster.health(wait_for_no_relocating_shards=True,wait_for_active_shards='all') 
0

您也可以撥打elasticsearch.Refresh(「博客」),如果你不想等待集羣刷新間隔