用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)
相关推荐
人工智能训练4 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
yaoming1684 小时前
python性能优化方案研究
python·性能优化
码云数智-大飞5 小时前
使用 Python 高效提取 PDF 中的表格数据并导出为 TXT 或 Excel
python
biuyyyxxx7 小时前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
极客数模7 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
小鸡吃米…8 小时前
机器学习中的代价函数
人工智能·python·机器学习
Li emily9 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
m0_561359679 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
Ulyanov10 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
2401_8384725110 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python