我必须在弹性中插入一个json数组。链接中可接受的答案建议在每个json条目之前插入标题行。答案是2岁,市场上是否有更好的解决方案?我需要手动编辑json文件吗?
[ { "id":9, "status":"This is cool." }, ... ]
好的,那么您可以使用简单的Shell脚本来完成一些非常简单的操作(请参见下文)。这个想法是不必手动编辑文件,而是让Python进行编辑并创建另一个文件格式符合_bulk端点期望的文件。它执行以下操作:
_bulk
bulk.sh:
#!/bin/sh # 0. Some constants to re-define to match your environment ES_HOST=localhost:9200 JSON_FILE_IN=/path/to/your/file.json JSON_FILE_OUT=/path/to/your/bulk.json # 1. Python code to transform your JSON file PYTHON="import json,sys; out = open('$JSON_FILE_OUT', 'w'); with open('$JSON_FILE_IN') as json_in: docs = json.loads(json_in.read()); for doc in docs: out.write('%s\n' % json.dumps({'index': {}})); out.write('%s\n' % json.dumps(doc, indent=0).replace('\n', '')); " # 2. run the Python script from step 1 python -c "$PYTHON" # 3. use the output file from step 2 in the curl command curl -s -XPOST $ES_HOST/index/type/_bulk --data-binary @$JSON_FILE_OUT
你需要:
bulk.sh
chmod u+x bulk.sh
./bulk.sh