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

标签 python elasticsearch elasticsearch-bulk-api elasticsearch-bulk

在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/

    相关文章:

    java - elasticsearch 6 ESIntegTestCase "codebase property already set"

    java - 如何在 Spring-data-elasticsearch 中禁用页面查询

    search - ElasticSearch不返回结果

    python - 带有选择的异步套接字 - Python

    python - PyCharm - 预期类型 'Optional[IO[str]]' ,取而代之的是 'TextIOWrapper[str]'

    python - Kivy 多显示器

    javascript - ElasticSearch 删除批量项目

    json - 如何批量更改Elastic Search的JSON格式

    python - django 模型上的 who 和 who