用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)
相关推荐
小陈的进阶之路5 小时前
Claude Code辅助测试:导入篇skills
python·自动化
whcyhhh6 小时前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
for_ever_love__7 小时前
python基础语法学习: 闭包
开发语言·python·学习·闭包
ly76897 小时前
Python 全面入门:从核心语法到工程实践
开发语言·python
Niuguangshuo8 小时前
DeepFilterNet 3:端侧实时全带降噪的开源标杆
python
第一程序员9 小时前
AI 辅助编程的 7 个误区:把模型当高级搜索引擎是对它的最大浪费
python·rust·github
Groundwork Explorer10 小时前
W5500 网卡编程初始化与使用指南
python·单片机
逸Y 仙X11 小时前
MCP(模型控制协议)完全指南:从核心概念到实战开发
python·大模型·llm·ai编程·mcp
WILLF11 小时前
前端视角:Python requests vs JS axios
前端·python
哒哒哒52852011 小时前
69. Python: 核心语法-面向对象基础-案例(教务系统)
python