【发布时间】:2018-07-19 15:40:19
【问题描述】:
我正在使用以下查询(使用 NodeJS 适配器)来定位集合中缺失的索引。
findIndexGaps(collection, index, from, to, callback) {
var aggregateOptions = [
{ $group: {_id: null, min: {$min: from}, max: {$max: to} } },
{ $addFields: {rangeIds: {$range: ['$min', '$max'] } } },
{ $lookup: {from: collection, localField: 'rangeIds', foreignField: index, as: 'entries'} },
{ $project: {_id: 0, missingIds: { $setDifference: ['$rangeIds', '$entries.'+index]}}}
];
this.connection.collection(collection).aggregate(aggregateOptions, {allowDiskUse: true}).toArray(...);
}
我已经为该集合设置了一个唯一索引item_id。当我使用参数from = 0、to = 50 和 index = 'item_id' 时,查询返回正确的结果。但是,执行需要将近 9 秒,这对于最多返回 50 个结果的查询来说是不可接受的。
我正在查询的集合非常大。在撰写本文时,它包含大约 4200 万个条目,并且每月以大约 1000 万的速度增长。我可以处理较小的查询范围(如上例中使用的 50 个),但我希望这些查询尽可能高效。
是什么导致了这种放缓,我该如何优化?
【问题讨论】: