2017-02-27 88 views
3

我在python中使用這段代碼來更新elasticsearch中的文檔。它工作正常,但很難將其用於數百萬個文檔,因爲我必須每次初始化id值來更新每個文檔。Elastisearch通過查詢更新

from elasticsearch import Elasticsearch, exceptions 

elasticsearch = Elasticsearch() 

elasticsearch.update(index='testindex', doc_type='AAA', id='AVpwMmhnpIpyZkmdMQkT', 
       body={ 
        'doc':{'Device': 'updated'} 
       } 
       ) 

我的Elasticsearch文檔中讀取,這還沒有包括在內,但: https://www.elastic.co/guide/en/elasticsearch/reference/current/_updating_documents.html

Note that as of this writing, updates can only be performed on a single document at a time. In the future, Elasticsearch might provide the ability to update multiple documents given a query condition (like an SQL UPDATE-WHERE statement).

+0

我很確定''update_by_query'獲取作爲q應該工作的參數。只需檢查此python http://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.update_by_query – christinabo

+0

你好AhmyOhlin,歡迎來到該網站。我編輯了您的問題以匹配本網站上其他問題的格式,請隨時再次編輯它。 – MackM

+0

@christinabo 我想將設備的值從'Boiler'更改爲'Test'。 我使用參數q ='設備:「鍋爐」'更新所有文檔的值'鍋爐',但我得到以下錯誤: TypeError:更新()有一個意想不到的關鍵字參數'q' 這是我的代碼 'elasticsearch.update(index ='testindex',doc_type ='AAA',q ='Device:「Boiler」', body = {'doc':{'Device':'TESTs'} }' – AhmyOhlin

回答

3

使用update_by_query(不是update)和script,你應該能夠更新文檔匹配您的查詢。

q = { 
    "script": { 
     "inline": "ctx._source.Device='Test'", 
     "lang": "painless" 
    }, 
    "query": { 
     "match": { 
      "Device": "Boiler" 
     } 
    } 
} 

es.update_by_query(body=q, doc_type='AAA', index='testindex') 

上面的工作適合我。 q查找與您的查詢匹配的文檔,腳本使用每個文檔的_source更新值。

我希望它也適用於您,可能對您想要使用的查詢進行一些調整。

+0

我試過你的代碼,它工作正常。感謝您的幫助。 – AhmyOhlin

+0

有沒有辦法做到這一點作爲upsert? – Iluvatar14