簡體   English   中英

如何將已創建的json格式字符串插入Elasticsearch Bulk

[英]How to insert an already created json-format string to Elasticsearch Bulk

在python腳本中,

我正在嘗試elasticsearch.helpers.bulk存儲多個記錄。

我將從另一個軟件中獲取json格式的字符串,並將其附加到源代碼部分中

我得到了這個答案的helpers.bulk格式

我的代碼的一部分:

def saveES(output,name):
    es = Elasticsearch([{'host':'localhost','port':9200}]) 
    output = output.split('\n')
    i=0
    datas=[]
    while i<len(output):
            data = {
                    "_index":"name",
                    "_type":"typed",
                    "_id":saveES.counter,
                    "_source":[[PROBLEM]]
            }
            i+=1
            saveES.counter+=1
            datas.append(data)

    helpers.bulk(es, datas)

我想在[[問題]]中附加一個json格式的字符串

我該如何安裝它? 我已經盡力了,但是輸出不正確。

如果我使用:

"_source":{
"image_name":'"'+name+'",'+output[i]
}

並且打印數據的結果是:

{'_type': 'typed', '_id': 0, '_source': {'image_name': '"nginx","features": "os,disk,package", "emit_shortname": "f0b03efe94ec", "timestamp": "2017-08-18T17:25:46+0900", "docker_image_tag": "latest"'}, '_index': 'name'}

這個結果表明,合並為一個字符串。

但我期望:

{'_type': 'typed', '_id': 0, '_source': {'image_name': 'nginx','features': 'os,disk,package', 'emit_shortname': 'f0b03efe94ec', 'timestamp': '2017-08-18T17:25:46+0900', 'docker_image_tag': 'latest'}, '_index': 'name'}

您的代碼中有很多問題。

  1. 您可以在循環中覆蓋data
  2. 您不遵守任何規范(Pesp8之類的東西)
  3. 你是一段時間,而不是理解列表
  4. 您創建了2個無用的變量
  5. 您可以在函數中實例化es

這是您改進的代碼

es = Elasticsearch([{'host':'localhost','port':9200}]) # You don't have to initialise this variable every time you are calling the function but only once.


def save_es(output,es):  # Peps8 convention
    output = output.split('\n') # you don't need a while loop. A comprehension loop will avoid a lot of trouble
    data = [    # Please without s in data
       {
          "_index": "name",
          "_type": "typed",
          "_id": index,
          "_source": {
              "image_name":"name" + name}
        }
        for index, name in enumerate(output)
    ]    
    helpers.bulk(es, data)

save_es(output, es)

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM