【问题标题】:Insert 271 million records to MongoDB向 MongoDB 插入 2.71 亿条记录
【发布时间】:2020-02-21 03:28:39
【问题描述】:

我有 2.71 亿条记录,逐行添加到需要添加到 MongoDB 的文本文件中,我正在使用 Python 和 Pymongo 来执行此操作。

我首先将包含 2.71 亿条记录的单个文件拆分为多个文件,每个文件包含 100 万行,并编写了当前代码将其添加到数据库中:

import os
import threading
from pymongo import MongoClient


class UserDb:
    def __init__(self):
        self.client = MongoClient('localhost', 27017)
        self.data = self.client.large_data.data


threadlist = []

def start_add(listname):
    db = UserDb()
    with open(listname, "r") as r:
        for line in r:
            if line is None:
                return
            a = dict()
            a['no'] = line.strip()
            db.data.insert_one(a)
    print(listname, "Done!")


for x in os.listdir(os.getcwd()):
    if x.startswith('li'):
        t = threading.Thread(target=start_add, args=(x,))
        t.start()
        threadlist.append(t)

print("All threads started!")


for thread in threadlist:
    thread.join()

这会启动与文件一样多的线程,并将每一行添加到数据库中。不好的是,3小时后它只增加了8.630.623。

怎样做才能更快地添加记录?

一行数据只有8位:(例如12345678)

【问题讨论】:

  • 性能问题可能由多种原因引起。我首先要看的是使用 IOSTAT 的磁盘性能。很多时候,这些类型的事情都与在硬盘驱动器上排队有关。如果硬件是问题,您可以升级硬件(水平扩展),或通过分片添加计算机(水平扩展)。其他要查看的内容包括文档架构本身以及是否可以改进。另外,试试看是否出现网络瓶颈...
  • 如果你的数据是csv或者json,看mongoimport

标签: python mongodb pymongo


【解决方案1】:

与其做多个insert_ones,不如看看bulk write operators

试一试,看看什么效果最好;我发现有 10,000 个批次适合我,但这取决于硬件。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多