用Python将JSON格式文件数据导入到Elasticsearch上

安装elasticsearch sdk

pip install elasticsearch

示例代码

python 复制代码
from elasticsearch import Elasticsearch # type: ignore
import json

username = "your username"
password = "your password"


es = Elasticsearch("https://your server ip:9200", ca_certs="/your ca_certs path/certs/http_ca.crt", # 指定 CA 证书路径
    basic_auth=(username, password)
)

class TestDataModel:
    def __init__(self, data):
        self.data1 = data.get("data1", None)
        self.data2 = data.get("data2", None)
        self.data3 = data.get("data3", None)
        self.data4 = data.get("data4", None)

def readjson2elasticsearch(file_path, es):
    if es.ping():
        print("连接成功")
        if not es.indices.exists(index="test_index"):
            es.indices.create(index="test_index", mappings={
                "properties": {
                    "data1": {"type": "text", "fields": {"raw": {"type": "keyword"}}},
                    "data2": {"type": "text", "index": False},
                    "data3": {"type": "text"},
                    "data4": {"type": "object"}
                }
            })
            print("索引 test_index 创建成功")

        with open(file_path, 'r') as f:
            count = 0
            for line in f:
                data = json.loads(line.strip())
                model = TestDataModel(data)
                es.index(index="test_index", document={
                        "data1": model.data1,
                        "data2": model.data2,
                        "data3": model.data3,
                        "data4": model.data4
                    })
                count += 1
                print(f"已导入 {count} 条数据")
                    
            
        print("数据导入完成")

    else:
        print("连接失败")


# es.indices.delete(index="test_index")


file_path = "/your data path/test_json_data.txt"
readjson2elasticsearch(file_path, es)
相关推荐
北冥有羽Victoria3 分钟前
OpenCLI 操作网页 从0到1完整实操指南
vscode·爬虫·python·github·api·ai编程·opencli
handsomestWei5 分钟前
scikit-learn数据预处理模块
python·机器学习·scikit-learn
w_t_y_y9 分钟前
机器学习常用的python包(二)工具箱scikit-learn
python·机器学习·scikit-learn
用户83562907805119 分钟前
Python 自动拆分 Word 文档教程:按分节符与分页符处理
后端·python
陈天伟教授22 分钟前
心电心音同步分析-案例:原型设计一
开发语言·人工智能·python·语言模型·架构
我的xiaodoujiao22 分钟前
API 接口自动化测试详细图文教程学习系列9--Requests模块
python·学习·测试工具·pytest
Allen_LVyingbo24 分钟前
量子计算Dirac Notation基本教学—从零基础到读懂量子信息论文(下)
开发语言·人工智能·python·数学建模·量子计算
Dxy12393102161 小时前
Python路径算法简介
开发语言·python·算法
躺平的赶海人1 小时前
python opencv实现相机内参标定之安装OpenCv
python·opencv·计算机视觉
满满和米兜1 小时前
【Java基础】-I/O-字符流
java·开发语言·python