我想使用搜索索引索引大约20个目录,每个目录包含大约10,000个文件。我希望操作需要几个小时,而且所有的数据都无法放入内存中,我希望一次对添加的内容进行批次,比如10或20。
基本代码如下所示,创建一个搜索索引,并在它准备好时执行一个回调函数,其中包含实例'si‘:
searchIndex(siOptions, (sierr, si) => {
// here I list the files and want to do batch adds:
while (true) {
var batch = getBatch();
if (!batch) break;
si.add(batch, options, (err) => {
console.timeEnd('batch');
});
}
});因此,我的基本想法是循环遍历目录,写出正在处理该目录的内容,列出文件,并将文件分批处理,比如每次处理20个文件:
_.each(subDirs, dir => {
// list files
// pull 20 files at a time
// do add above
});所以我知道该怎么做,但是看起来很难看。能够同步运行将是理想的,但有什么实用程序库我可以使用吗?我的想法是创建一个函数来处理一个目录并一次遍历一个目录,然后在回调中增加计数器并调用自己.
var dirIndex = 0;
var doDir = function(cbDir) {
if (dirIndex >= dirs.length) cbDir(); // done
var batches = _.chunk(fs.readdirSync(dirs[dirIndex]), 20);
var batchIndex = 0;
var doBatch = function(cbBatch) {
if (batchIndex >= batches.length) {
cbBatch();
return;
}
console.time('batch');
si.add(batch[batchIndex++], options, (err) => {
doBatch(cbBatch); // process next batch, have it call our callback
});
};
doBatch(() => doDir(cbDir)); // final callback will do next dir
}看起来,我可能会把自己敞开心扉,面对范围可变的问题。有更好的办法吗?我一直假设搜索索引不会有问题,因为函数searchIndex(siOptions, (sierr, si) => {在所有操作完成之前就返回了.
发布于 2016-08-19 09:17:59
如果要同步运行代码,可以尝试setTimeout()
https://stackoverflow.com/questions/39034885
复制相似问题