Json 在elasticsearch中插入多个文档
我必须在elastic中插入一个json数组。链接中接受的答案建议在每个json条目之前插入一个标题行。答案是2年前,市场上有没有更好的解决方案?我需要手动编辑json文件吗Json 在elasticsearch中插入多个文档,json,
elasticsearch,Json,
elasticsearch,我必须在elastic中插入一个json数组。链接中接受的答案建议在每个json条目之前插入一个标题行。答案是2年前,市场上有没有更好的解决方案?我需要手动编辑json文件吗 好的,那么您可以使用一个简单的shell脚本来做一些非常简单的事情(见下文)。这样做的目的是不必手动编辑文件,而是让Python来做,并创建另一个格式符合预期的文件。它做了以下工作: 首先,我们声明一个小Python脚本,该脚本读取JSON文件并创建一个具有所需文件格式的新文件,以发送到\u bulk端点 然后,我们运行
好的,那么您可以使用一个简单的shell脚本来做一些非常简单的事情(见下文)。这样做的目的是不必手动编辑文件,而是让Python来做,并创建另一个格式符合预期的文件。它做了以下工作:
\u bulk
端点\u bulk
端点#!/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(即chmod u+x bulk.sh
)/bulk.sh
如何读取JSON文件?i、 你在用什么客户端语言?在我的机器上。我正在使用命令行中的curl,使用elastic进行演示。您能展示JSON文件的摘录吗?@Val更新了问题。太棒了,很高兴它成功了!!对于Elasticsearch的最新版本,您需要使用
-H'content-type:application/x-ndjson'
将内容类型添加到curl请求中,我知道这是一个相当老的线程,但这是一个问题。每当我在JSON文件中使用它时,它会在每个字符处添加一个索引字符串。还有其他人有这个问题吗?你是如何解决的?@ChristopherRadkins可以随意创建一个新问题来引用这个问题,并说明你的确切问题。@val提出了一个新问题,
#!/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