用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)
相关推荐
西瓜太郎12349 分钟前
request_id 如何串起请求、路由、计费和日志
后端·python
troy12810 分钟前
Python 基础语法(一):变量、数据类型与运算符
java·服务器·python
用户2986985301426 分钟前
Python 将 Word 文档转换为图片的实践指南
后端·python·api
弈栈录27 分钟前
LangChain Agent 实战:快速构建可调用工具的智能体
python·架构
宸津-代码粉碎机1 小时前
Spring AI 高危CVE漏洞深度复盘|生产禁跑版本汇总+临时防御+修复方案
java·大数据·人工智能·python·spring
承渊政道2 小时前
Python IDLE鸿蒙PC适配全记录:用 ArkUI 重建编辑、运行、Shell 与基础调试闭环
python·microsoft·harmonyos·鸿蒙系统·pc端
zjh9005302 小时前
Kotlin黑科技:空安全与Java兼容性深度解析
python
黄昏恋慕黎明2 小时前
博客论坛技术迭代
python·pytest
我叫汪枫2 小时前
RAG 进阶:切分、检索、重排序,以及它和 Agent、微调、MCP 都是什么关系
开发语言·python
冰芒芒2 小时前
构建你的第一个 Agent 项目
python