python - How to insert an already created json-format string to Elasticsearch Bulk -
in python script,
i'm trying elasticsearch.helpers.bulk store multiple records.
i json-format string software, , want attach in source part
i got helpers.bulk format answer
part of code:
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)
i attach json-format string in [[problem]]
how can attach in? have tried hard, not output in correct..
if use:
"_source":{ "image_name":'"'+name+'",'+output[i] }
and print data result is:
{'_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'}
this result show combined single string.
but expect:
{'_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'}
there many problems in code.
- you override value of
data
in loop - you don't respect norms (pesp8 , stuff)
- you while instead of comprehension list
- you created 2 useless variable
- you instantiate es in function
here improved code
es = elasticsearch([{'host':'localhost','port':9200}]) # don't have initialise variable every time calling function once. def save_es(output,es): # peps8 convention output = output.split('\n') # don't need while loop. comprehension loop avoid lot of trouble data = [ # please without s in data { "_index": "name", "_type": "typed", "_id": index, "_source": { "image_name":"name" + name} } index, name in enumerate(output) ] helpers.bulk(es, data) save_es(output, es)
hope help.
Comments
Post a Comment