在elasticsearch中插入多个文档

For*_*hit 4 json elasticsearch

我必须在弹性中插入一个json数组.链接中接受的答案建议在每个json条目之前插入标题行.答案是2年,市场上有更好的解决方案吗?我需要手动编辑我的json文件吗?

有没有办法在elasticsearch服务器中导入json文件(包含100个文档).

[
  {
    "id":9,
    "status":"This is cool."
  },
  ...
]
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 7

好的,那么使用简单的shell脚本就可以做到非常简单(见下文).我们的想法是不必手动编辑您的文件,但让Python执行此操作并创建另一个文件,其格式符合_bulk端点所需的格式.它执行以下操作:

  1. 首先,我们声明一个Python脚本,它读取您的JSON文件并创建一个新的文件,并将所需的文件格式发送到_bulk端点.
  2. 然后,我们运行该Python脚本并存储批量文件
  3. 最后,我们_bulk使用简单的curl命令将步骤2中创建的文件发送到端点
  4. 你去了,你现在有一个包含你的文件的新ES索引

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
Run Code Online (Sandbox Code Playgroud)

你需要:

  1. 将上面的脚本保存在bulk.sh文件中并chmod它(即chmod u+x bulk.sh)
  2. 修改ordre顶部的三个变量(步骤0)以匹配您的环境
  3. 用它来运行它 ./bulk.sh