3

这是我想并行化的伪代码,但不知道从哪里开始

from pymongo import MongoClient


client = MongoClient('localhost', 27017)
db = client['myDB']
collection = db.myCollection

test_list = ['foo', 'bar']
result_list = list()

for el in test_list:
     result_list.append(collection.distinct('attrib',{'version': el}))

我知道如何使用 joblib 创建并行循环,但我不确定如何并行查询 MongoDB,我应该创建多个客户端还是集合?如果我只是用 joblib 重写它而不关心 MongoDB,上面的代码会起作用吗?

4

1 回答 1

1

您可以在单独的线程中运行请求:

from multiprocessing.dummy import Pool as ThreadPool 

from pymongo import MongoClient


client = MongoClient('localhost', 27017)
db = client['myDB']
collection = db.myCollection

thread_pool_size = 4
pool = ThreadPool(thread_pool_size) 

def my_function(el):
    return collection.distinct('attrib', {'version': el}))

test_list = ['foo', 'bar']
result_list = pool.map(my_function, test_list)
于 2018-08-30T16:23:40.720 回答