python使用elasticsearch批量追加更新,條件更新

使用 doc更新數據,原數據會被覆蓋,如果要更新一個列表,追加而不是覆蓋。那麼doc就不符合這個業務場景了。
這時可以通過script腳本處理追加數據

更新前
更新前

from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

es = Elasticsearch("localhost:9200")
docs = [
	# 對字符串的追加更新
    {"_op_type": "update", "_index": "test_index1", "_type": "test_type", "_id": "001", "script": {"inline":"ctx._source.name+=params.tag","params":{"tag":"黃曉明"}}},
    # 對列表的追加更新
    {"_op_type": "update", "_index": "test_index1", "_type": "test_type", "_id": "002","script": {"inline":"ctx._source.names.add(params.tag)","params":{"tag":{"adc":"666"}}}}
]
# 批量更新
bulk(client=es, actions=docs, chunk_size=len(docs))

更新後
更新後

注意:我之前使用的5.2.0版本沒有script功能,試了半天都失敗了差點懷疑人生。更換了5.6版本之後發現支持了script,具體什麼原因沒有深究

接下來是條件更新

update_doc = {
  "script": {
    "inline": "if(ctx._source.age==params.age && ctx._source.names!=null)
    {ctx._source.names.add(params.tag)}",
    "params": {"tag": {"adc": "634366"}, "age": 1000}
  }
}
es.update_by_query(index="test_index1", doc_type="test_type", body=update_doc)

這條語句的意思是,如果age爲1000,並且names這個數組存在,則對數組進行追加更新。
因爲如果names數組不存在,進行更新的話,會報錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章