【问题标题】:Index JSON files in elasticsearch using Python?使用Python在elasticsearch中索引JSON文件?
【发布时间】:2017-10-14 08:15:10
【问题描述】:

我有一堆JSON文件(100个),分别命名为merged_file 1.json、merged_file 2.json等等。

如何使用 python(elasticsearch_dsl) 将所有这些文件索引到 elasticsearch 中?

我正在使用此代码,但它似乎不起作用:

from elasticsearch_dsl import Elasticsearch
import json
import os
import sys

es = Elasticsearch()

json_docs =[]

directory = sys.argv[1]

for filename in os.listdir(directory):
    if filename.endswith('.json'):
        with open(filename,'r') as open_file:
            json_docs.append(json.load(open_file))

es.bulk("index_name", "type_name", json_docs)

JSON 看起来像这样:

{"one":["some data"],"two":["some other data"],"three":["other data"]}

我能做些什么来纠正这个错误?

【问题讨论】:

  • 你能展示一下 jsondocs 的样子吗?
  • 您在每个文档之前都缺少命令行。有关详细信息,请参阅here
  • @BhargaviSri - 已添加

标签: python json elasticsearch elasticsearch-dsl


【解决方案1】:

对于这个任务,你应该使用elasticsearch-py (pip install elasticsearch):

from elasticsearch import Elasticsearch, helpers
import sys, json

es = Elasticsearch()

def load_json(directory):
    " Use a generator, no need to load all in memory"
    for filename in os.listdir(directory):
        if filename.endswith('.json'):
            with open(filename,'r') as open_file:
                yield json.load(open_file)

helpers.bulk(es, load_json(sys.argv[1]), index='my-index', doc_type='my-type')

【讨论】:

  • 如何获取被索引的 jsons 的 id?
  • 如果您关心 ids(否则,elasticsearch 会为您创建随机的),只需在您的 json 中直接添加一个 _id 字段,或者将文件名放在那里或其他东西
  • 这会在bulk的action参数中抛出错误。 """ ~\Anaconda3\lib\site-packages\elasticsearch\helpers\actions.py in expand_action(data) 25 # 确保我们不改变动作 26 data = data.copy() ---> 27 op_type = data.pop("_op_type", "index") 28 action = {op_type: {}} 29 for key in ( TypeError: pop() 最多接受 1 个参数(给定 2 个)"""
猜你喜欢
  • 2018-08-31
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2020-03-10
  • 2015-08-16
  • 1970-01-01
  • 2021-02-27
  • 2021-10-24
相关资源
最近更新 更多