gpt4 book ai didi

python - 如何将已创建的json格式字符串插入Elasticsearch Bulk

转载 作者:行者123 更新时间:2023-12-03 00:04:56 25 4
gpt4 key购买 nike

在python脚本中,

我正在尝试 elasticsearch.helpers.bulk 来存储多个记录。

我将从另一个软件中获取json格式的字符串,并将其附加到源代码部分中

我通过此answer获得了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'}

最佳答案

您的代码中有很多问题。

  • 您可以在循环
  • 中覆盖 data的值
  • 您不遵守任何规范(Pesp8和其他内容)
  • 而不是理解列表
  • 您创建了2个无用的变量
  • 您可以在函数
  • 中实例化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)

    希望对您有所帮助。

    关于python - 如何将已创建的json格式字符串插入Elasticsearch Bulk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45747585/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com