Python3导入少量Json文件到ElasticSearch 7.x

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,后续将更新到我的文章中

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值