用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)
相关推荐
方也_arkling6 分钟前
【大模型】初步认识RAG
人工智能·python
迁旭26 分钟前
prompt_toolkit 3.0.52 API 参考手册
python
WL_Aurora28 分钟前
Python 算法基础篇之堆和优先队列
python·算法
早日退休!!!29 分钟前
PyTorch适配NPU
人工智能·pytorch·python
刀法如飞37 分钟前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
xingpanvip42 分钟前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
vortex51 小时前
Villain:新一代轻量级 C2 框架完整使用指南
python·网络安全·kali·c2
测试员周周1 小时前
【AI测试系统】第5篇:AI 编码工具抛硬币?我们用 LangGraph 做了个“确定性+AI”的测试系统(附自愈架构)
人工智能·python·功能测试·测试工具·架构·langchain·单元测试
Levin__NLP_CV_AIGC1 小时前
py文件中文件复制方法
开发语言·python
庚昀◟2 小时前
腾讯云 CVM + Docker + Jenkins + GitLab CI/CD 全流程指南(python、flask实现简单计算器)
python·ci/cd·docker·flask·jenkins