使用Python在elasticsearch中索引JSON文件?

8
我有一堆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的样子吗? - sleepophile
你需要在每个文档之前添加命令行。更多详情请参见这里 - Val
@BhargaviSri - 已添加 - anshaj
1个回答

12

对于这个任务,您应该使用 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')

我该如何获取已索引的JSON的ID? - anshaj
3
如果您关心文档的ID(否则Elasticsearch会为您创建随机ID),只需在您的JSON中添加一个_id字段,可以直接将其命名或者使用文件名等其他方式。 - Honza Král
这在bulk的action参数中引发错误。 """ ~\Anaconda3\lib\site-packages\elasticsearch\helpers\actions.py in expand_action(data) 25 # make sure we don't alter the action 26 data = data.copy() ---> 27 op_type = data.pop("_op_type", "index") 28 action = {op_type: {}} 29 for key in (TypeError: pop()最多接受1个参数(给定了2个)""" - Murtaza Haji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接