【问题标题】:Insert multiple documents in elasticsearch在elasticsearch中插入多个文档
【发布时间】:2015-11-29 18:09:15
【问题描述】:

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

is there any way to import a json file(contains 100 documents) in elasticsearch server.?

[
  {
    "id":9,
    "status":"This is cool."
  },
  ...
]

【问题讨论】:

  • 你如何读取你的 JSON 文件?即您使用的是什么客户端语言?
  • 它在我的机器上。我从命令行使用 curl 开始使用弹性。
  • 你能展示一段你的 JSON 文件吗?
  • @Val 更新问题。
  • 太棒了,很高兴它成功了!

标签: json elasticsearch


【解决方案1】:

好的,那么您可以使用一个简单的 shell 脚本来做一些非常简单的事情(见下文)。这个想法是不必手动编辑您的文件,而是让 Python 来完成并创建另一个格式符合 _bulk endpoint 期望的文件。它执行以下操作:

  1. 首先,我们声明一个小的 Python 脚本,该脚本读取您的 JSON 文件并创建一个具有所需文件格式的新脚本,以发送到 _bulk 端点。
  2. 然后,我们运行该 Python 脚本并存储批量文件
  3. 最后,我们使用简单的 curl 命令将步骤 2 中创建的文件发送到 _bulk 端点
  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

你需要:

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

【讨论】:

  • 对于最新版本的 Elasticsearch,您需要使用 -H 'Content-Type: application/x-ndjson' 将 content-type 添加到 curl 请求中
  • 我知道这是一个相当古老的线程,但这是一个问题。每当我在我的 JSON 文件上使用它时,它都会在每个字符处添加一个索引字符串。其他人有这个问题,你是怎么解决的?
  • @ChristopherAdkins 随意创建一个新问题来引用这个问题并说明您的确切问题。
  • @val 开了一个新问题,stackoverflow.com/questions/61580963/…
猜你喜欢
  • 2020-08-18
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-01-13
  • 1970-01-01
相关资源
最近更新 更多