我有一个超过 2500 万行的 15GB 文件,它是这种 json 格式(mongodb 接受导入:
[
{"_id": 1, "value": "\u041c\..."}
{"_id": 2, "value": "\u041d\..."}
...
]
当我尝试使用以下命令将其导入 mongodb 时,我得到的速度仅为每秒 50 行,这对我来说真的很慢。
mongoimport --db wordbase --collection sentences --type json --file C:\Users\Aleksandar\PycharmProjects\NLPSeminarska\my_file.json -jsonArray
当我尝试使用 python 和 pymongo 将数据插入集合时,速度更差。我也尝试过提高进程的优先级,但没有任何区别。
我尝试的下一件事是同样的事情,但没有使用 -jsonArray
,虽然我的速度有了很大的提高(~4000/秒),但它说提供的 JSON 的 BSON 表示太大了。
我还尝试将文件拆分为 5 个单独的文件,然后将它们从不同的控制台导入到同一个集合中,但我发现所有这些文件的速度都降低到了大约 20 个文档/秒。
当我在整个网络上搜索时,我看到人们的速度超过 8K 文档/秒,但我看不出我做错了什么。
有没有办法加快这件事,或者我应该将整个 json 文件转换为 bson 并以这种方式导入它,如果是的话,哪种是进行转换和导入的正确方法?
非常感谢。
最佳答案
我对 160Gb 的转储文件有完全相同的问题。我用了两天时间用 -jsonArray
加载了原始文件的 3%,并用了 15 分钟完成这些更改。
首先,删除开头的 [
和结尾的 ]
字符:
sed 's/^\[//; s/\]$/' -i filename.json
然后不使用 -jsonArray
选项导入:
mongoimport --db "dbname" --collection "collectionname" --file filename.json
如果文件很大,sed
将花费很长时间,而且您可能会遇到存储问题。你可以改用这个 C 程序(不是我写的,所有荣耀归于@guillermobox):
int main(int argc, char *argv[])
{
FILE * f;
const size_t buffersize = 2048;
size_t length, filesize, position;
char buffer[buffersize + 1];
if (argc < 2) {
fprintf(stderr, "Please provide file to mongofix!\n");
exit(EXIT_FAILURE);
};
f = fopen(argv[1], "r+");
/* get the full filesize */
fseek(f, 0, SEEK_END);
filesize = ftell(f);
/* Ignore the first character */
fseek(f, 1, SEEK_SET);
while (1) {
/* read chunks of buffersize size */
length = fread(buffer, 1, buffersize, f);
position = ftell(f);
/* write the same chunk, one character before */
fseek(f, position - length - 1, SEEK_SET);
fwrite(buffer, 1, length, f);
/* return to the reading position */
fseek(f, position, SEEK_SET);
/* we have finished when not all the buffer is read */
if (length != buffersize)
break;
}
/* truncate the file, with two less characters */
ftruncate(fileno(f), filesize - 2);
fclose(f);
return 0;
};
P.S.:我无权建议迁移这个问题,但我认为这可能会有所帮助。
关于json - 使用 -jsonArray 时 mongoimport 的速度非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27884838/