Python3导入Json文件到ElasticSearch 7.x
1、环境准备
Python 3.x
ES 7.x
2、pip安装elasticsearch库
在终端输入 pip install elasticsearch 安装
3、Python脚本
# -*- coding: utf-8 -*-
import json
import os
import elasticsearch
# 索引名称
_index = 'indexName'
# ES地址
es_url = 'localhost:9200/'
# 文件路径
file_path = 'D:/data/'
# 错误数统计
err_count = 0
# 存入数据
def put_json(file_name, err_count):
file = open(file_path + file_name, 'r', encoding='utf-8')
if file is None:
return
text = json.load(file)
print(text)
try:
es = elasticsearch.Elasticsearch([es_url])
es.index(index=_index, id=None, body=text)
except:
print("插入异常")
err_count += 1
# 读取所有文件的列表
for i in os.listdir(file_path):
print(i)
put_json(i, err_count)
print('finish')
print('err count ' + str(err_count))
4、PS
在ES7.x中,已经弱化了doc_type这个属性,通过查看源码可以看到python的ES源码自动把文本类型(doc_type)设置为"_doc"了
index是单条插入数据,还可以调用批量插入的api,后续将更新到我的文章中