当前位置:首页 > 日记本 > 正文内容

python 从数据库导入数据到elasticsearch

zhangchap1年前 (2023-03-29)日记本221
import pymysql
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

# 连接 MySQL
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='FiroRegePUE0000idB3',
    database='car',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

# 连接 Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

# 创建 Elasticsearch 索引
index_name = 'articles'
if not es.indices.exists(index=index_name):
    es.indices.create(index=index_name, ignore=400)

# 获取 MySQL 数据
with conn.cursor() as cursor:
    sql = 'SELECT * FROM yj_ask_1'
    cursor.execute(sql)
    articles = cursor.fetchall()

# 将 MySQL 数据导入 Elasticsearch
actions = []
for article in articles:
    action = {
        '_index': index_name,
        '_id': article['id'],
        '_source': {
            'title': article['title'],
            'content': article['content']
        }
    }
    actions.append(action)

bulk(es, actions)

# 关闭连接
conn.close()
es.transport.close()


分享给朋友:

相关文章

配置存储(IIS 7)

适用于:Windows 7,Windows Server 2008,Windows Server 2008 R2,Windows Vista IIS 7使用一种新的...

CDN下 Nginx开启PC/M识别跳到对应的域名下访问,css/js死循环问题

背景: 新做了一个网站:   服务器操作系统:Linux;   WEB服务器版本:nginx/1.16.1; 问题:...

lxml win 安装方法

文档地址:https://lxml.de/installation.htmlwindows 下安装不了的都可以在这里找:https://www.lfd.uci.edu/~gohl...

Nginx+PHP,PHP如何优化配置?

具体修改FPM配置文件参数: 若你的php日志出现: WARNING: [pool www] seems busy (you may need to increase pm.sta...

python使用mongodb数据库

from pymongo import MongoClient,collection class KSpdier(Thread):   ...

python xpath语法总结

python xpath语法总结:常用的://1.从任意节点开始/2.从根节点开始//div/p3.div下的p标签//div[@class="hrzz_bottom"]/ul/l...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。