当前位置:首页 > 数据库 > 正文内容

mysql数据导入es

root5年前 (2021-11-11)数据库1612

将mysql数据取出放到elasticsearch中


from datetime import datetime
from elasticsearch import Elasticsearch
import pymysql
import time
import json
from elasticsearch.helpers import bulk, streaming_bulk
import sys

from multiprocessing import Pool
tb_name = "test"
# es的索引
es_index = "index_" + tb_name
es_type = "type_" + tb_name

def db2es(x):
    i,j=x
    db = pymysql.connect("127.0.0.1", "root", "123456", "User", charset='utf8')
    es = Elasticsearch([{"host": "127.0.0.1", "port": 9200}], timeout=60, max_retries=3, retry_on_timeout=True)
    cursor = db.cursor()
    while True:
        print(time.strftime('%Y-%m-%d %H:%M:%S --> ') + str(i))
        sql = '''SELECT
                            id,
                            name,
                            age
                        FROM
                            ''' + tb_name + ''' limit %s, 100000;''' % i

        cursor.execute(sql)
        rows = cursor.fetchall()
        action = []
        if rows:
            for row in rows:
                (id, name, age) = row

                action.append({
                    "_index": es_index,
                    "_type": es_type,
                    "_id": id,
                    "_source": {
                        "name":name,
                        "age":age
                    }
                })
            # 导入es
            bulk(es, action)
            del action[0:len(action)]
            i = i + 100000
            if i >= j:
                print(i)
                break
        else:
            break
    print(time.strftime('%Y-%m-%d %H:%M:%S --> '), i, j)
    print(tb_name + " done")
    db.close()

if __name__ == '__main__':
	# 多进程运行
    pool = Pool(processes=8)
    db = pymysql.connect("127.0.0.1", "root", "123456", "User", charset='utf8')
    cursor = db.cursor()
    sql = "SELECT COUNT(*) FROM test;"
    cursor.execute(sql)
    rows = cursor.fetchone()[0]
    db.close()
    args=[(i, i+5000000 if rows>(i+5000000)else rows) for i in range(0,rows,5000000)]
    pool.map(db2es,args)
    pool.close()
    pool.join()


扫描二维码推送至手机访问。

版权声明:本文由一叶知秋发布,如需转载请注明出处。

本文链接:https://www.zhiqiu.top/?id=173

分享给朋友:

相关文章

postgresql 导入导出sql 文件

pg_dump  -h localhost -U postgres -t tablename databasename >./test.sql导出 -t 表名  psql -d test1 -U...

centos7 安装mysql

centos7 安装mysql

下载rpm包wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm 安裝包仓库yum -y install * 或者yum -...

清空postgresql的缓存

系统:centos,版本:postgresql-9.6因为要测试postgresql的性能,当多次查询的时候查询结果会因为缓存用时很短,不能模拟出现实使用的场景。因此需要清除缓存。首先stop掉postgresqlsystemctl sto...

postgresql 查看数据库、表的大小

查看数据库的大小 select pg_database_size('test'); select pg_size_pretty(pg_database_size('test');查看单...

clickhouse 搭建

通过docker 部署clickhousedocker-compose文件内容如下:services:     ipwave-clickhouse:     ...