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

python 从数据库导入数据到elasticsearch

zhangchap1年前 (2023-03-29)日记本226
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()


分享给朋友:

相关文章

网络编辑工具箱注册ComCtl32.ocx

1.把ComCtl32.ocx放到c:\Windows\SysWOW64,注:需要管理员权限 2.打开C:\Windows\System32 找到 cmd.exe 鼠标右键管理员身份...

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 jieba分词

import jieba from jieba.analyse import tfidf words = jieba.lcut('...

python读取txt文件放到Queue队列

from queue import Queue with open('kw.txt',encoding='utf-8')&nb...

python fake_useragent 模块用法

我们每次发送requests请求时通过random从中随机获取一个随机UserAgent,两行代码即可完成UserAgent的不停更换 from fake_useragent i...

发表评论

访客

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