栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

通过python将mongodb的数据库批量导入elasticsearch

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过python将mongodb的数据库批量导入elasticsearch

from threading import Thread
from queue import Queue
from pymongo import MongoClient, collection
from elasticsearch import Elasticsearch, client
from hashlib import md5  #哈希函数  
import time
class Putdata(Thread):
    def __init__(self,queue:Queue,config:dict):
        super(Putdata, self).__init__()
        self.queue = queue
        self.config = config

    def run(self):
        while True:
            try:
                title,content = self.queue.get()
                self.put_document(title,content)            
            finally:
                self.queue.task_done()
    @staticmethod
    def get_hash(title):
        return md5(title.encode('utf-8')).hexdigest()
    def put_document(self,title,content):
        doc = {
            'title': title,
            'content': content,
        }
        _id = self.get_hash(title)
        self.config['es'].index(index = self.config['index'],document=doc,id=_id,ignore=[400,409,500])
def read_data(table: collection.Collection,queue: Queue):
    article = table.find({},{'_id':0,'title':1,'content':1})
    for item in article:
        queue.put((item['title'],item['content']))


if __name__ =="__main__":
    article_queue = Queue()
    client = MongoClient()
    db = client['yikaowang']
    es = Elasticsearch(hosts='http://127.0.0.1:9200/')
    put_config = {
        'es':es,
        'index':'wenzhang',
    }
    rd = Thread(target=read_data,args=(db['wenzhang'],article_queue))
    rd.daemon = True
    rd.start()
    time.sleep(2)
    for _ in range(50):
        pd = Putdata(article_queue,put_config)
        pd.daemon = True
        pd.start()
    article_queue.join()
    print('成功入es')
    
        


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/689175.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号