首页 > 解决方案 > 大数据查询mongodb、聚合、单索引或复合索引

问题描述

我正在尝试加快对包含超过 1000 万个文档的集合执行的查询。文档示例如下所示

    {
        nMove: 2041242,
        typeMove: 'Sold',
        date: "2016-05-18T16:00:00Z",
        operation: 'output',
        origin: {
            id: '3234fds32fds42',
            name: 'Main storage',
        },
        products: [{
           id: '342fmdsff23324432',
           name: 'Product 1',
           price: 34,
           quantity: 9
        }],
    }

现在我必须查询与给定的“product.id”或“origin.id”或两者都匹配的所有文档,并计算 product.quantity 的总数量。

所以我正在执行这样的查询。

 movesModel.aggregate([
    {
        $match: {
            $expr: {
                $and: [
                    { $in: [req.params.idProduct, '$product.id'] },
                    { $eq: ['$origin.id', req.params.idOrigin }] },
                ]
            }
        }
    },
    {
        $project: {
            _id: 0,
            outputs: {
                $sum: {
                    $cond: { if: { $eq: ['$operation', 'input'] }, then: '$product.quantity', else: 0 }
                }
            },
            inputs: {
                $sum: {
                    $cond: { if: { $eq: ['$operation', 'output'] }, then: '$product.quantity', else: 0 }
                }
            }
        }
    },
    {
        $group: {
            _id: '$_id',
            inputs: { $sum: '$inputs' },
            outputs: { $sum: '$outputs' }
        }
    },

]).then((result) => {
    res.json(result)
})

此查询大约需要 1 分钟才能解决...有时此查询 $match 与超过 200k 文档...考虑到我不需要全部数据,我只需要数量的总和...我有一些问题......(我是mongodb noob)

  1. 关于索引.. 我创建了一个复合索引 db.moves.createIndex({ 'origin.id': 1, 'product.id':1})。这是对的吗?我应该改变它吗?

  2. 我的查询可以吗?我可以改进吗?

  3. 为了防止查询与 200k 文档匹配……我做了一些棘手的事情。我添加了一个名为“日期”的字段,我想获取与“origin.id”、“product.id”匹配且为 $gte: date 的所有文档,但它需要相同的时间......甚至当它只匹配 1 个文档时...

  4. 完成......我认为,我遇到的所有问题都与索引有关......所以我试图检查我的 indexStats......但它似乎不适用于我的聚合查询。

任何帮助表示赞赏。谢谢你

///////////完整管道///////////

在这种情况下,我还有两个名为“存储”和“库存”的集合

//storage examples
    {
     _id: '3234fds32fds42'
     name: 'Main storage'
     status: true
    }
    {
    _id: '32f32f32432sda'
    name: 'Other storage'
    status: true
    }

//invetories examples
{
    _id: 'fvavcsa3a3aa3'
    date: '2020-01-01'
    storage: {
             _id: '3234fds32fds42'
            name: 'Main storage'
             }
    products: [{
               id: '342fmdsff23324432',
               name: 'Product 1',
            }],
}

所以这就是我使用 $lookup 的原因,我真正需要的是获得与每个存储和产品匹配的所有动作。

//我还添加了清单以按日期过滤并防止匹配大量文档

所以这是我的查询。

    storagesModel.aggregation([
     {
       $match: { status: true }
     },
     {
            $lookup: {
                from: 'inventories',
                as: 'inventory',
                let: { "idStorage": "$_id" },
                pipeline: [
                    {
                        $match: {
                            $expr: {
                                $and: [
                                    { $eq: ['$storage._id', { $toString: "$$idStorage" }] },
                                    { $in: [req.params.id, '$products._id'] }
                                ]
                            }
                        },
                    },
                    {
                        $sort: { date: -1 } // TO TAKE THE LAST INVENTORY
                    },
                    {
                        $limit: 1
                    }

                ]
            }
     },
     { $unwind: { path: '$inventories', preserveNullAndEmptyArrays: true } }, //DECONSTRUCT THE ARRAY AND GET IT AS OBJECT
     {
        $lookup: {
              from: 'moves',
              as: 'moves',
              let: { 
              "idStorage": "$_id",
              'date': '$inventory.date'},
              pipeline: [
                         {
                          $match: {
                                 $expr: {
                                       $and: [
                                          { $gte: ['$date', $$date] } 
                                          { $eq: ['$origin.id', '$$idStorage' }] },
                                          { $in: [req.params.idProduct, '$product.id'] },                                         
                                             ]
                                        }
                                  }
                          },
                          {
                            $project: {
                                     _id: 0,
                                     outputs: {
                                            $sum: {
                                                 $cond: { if: { $eq: ['$operation', 'input'] }, then: '$product.quantity', else: 0 }
                                                   }
                                               },
                                     inputs: {
                                            $sum: {
                                                 $cond: { if: { $eq: ['$operation', 'output'] }, then: '$product.quantity', else: 0 }
                                                   }
                                             }
                                        }
                         },
                         {
                          $group: {
                          _id: '$_id',
                          inputs: { $sum: '$inputs' },
                          outputs: { $sum: '$outputs' }
                          }
                   },
             ]
        }
    ])

总结...

我需要得到的是产品在每个存储中的“移动”总数。考虑到也许有一个“清单”可以给你一个日期来防止匹配很多文件。这就是为什么我使用 storageModel 并使用 $lookup 阶段来获取最后一个库存,所以我有 $$date 和 $$idStorage。然后我使用'moves'集合中的$lookup...我知道这是一个繁重的查询但是...我认为给出一个日期并使用适当的复合索引应该很快...但即使我尝试获取一个只有很少“动作”的产品的“动作”……大约需要 20 或 30 秒……

我尝试在没有 $lookup 的情况下进行单个查询,甚至匹配 400k 文档需要 1-2 秒...

你有什么想法?谢谢你的帮助

标签: mongodbmongodb-indexes

解决方案


总的来说,您做得很好,让我们回顾一下您的观点并分别讨论。

  1. 是的,这太棒了,复合索引正是这条管道所需要的。我相信您在选择创建复合索引之前已经阅读过复合索引,因此我不会深入探讨为什么这个索引是最优的,因为它是微不足道的。

  2. 让我们把这个留到最后。

  3. 太好了,如果您不关心整个数据样本而只关心最近的数据,这是可行的方法,现在为了正确利用此字段来提高性能,您应该转储我们在第 1 部分中讨论的旧索引和创建一个新的复合索引以包含此字段,{date: -1, 'origin.id': 1, 'product.id': 1}请注意我们为日期选择了一个递减索引,因为我们想要最新的数据。这将使它更有效率。

由于您必须阅读过复合索引字段顺序很重要,因此请随意更改此顺序以匹配您最常进行的查询。

  1. 然而,Mongo 生成索引树的方式不太可能不稳定,我的意思是,如果您很久以前创建了索引,并且从那时起有更多数据进入,您可能会从删除和重新构建索引中受益。话虽如此,我不建议这样做,因为我觉得在您的情况下任何改进都会有些微不足道。

  2. (2) 回到您的查询,首先我想问两件事:(a) 您$and在匹配查询中使用过,但根据您的措辞描述,逻辑似乎$or更合适。这是一个快速更改,如果需要,您可以这样做。(b) 我再次不确定这是否是一个错误,但您似乎已将input's 转换为 'output's,反之亦然。如果是这种情况,您应该切换它们。

话虽如此,我将如何重写这个查询(剧透没有太大变化):

movesModel.aggregate([
    { // notice i'm using Mongo's dot notation, $expr is also fine. not sure if there's an efficiency difference
        $match: {
            $and: [
                {
                    $or: [
                        {
                            "product.id": req.params.idProduct
                        },
                        {
                            "origin.id": req.params.idOrigin
                        }
                    ]
                },
                {
                    date: {$gt: new Date("2020-01-01")}
                }
            ]
        }
    },
    {  // there's no need for the project stage as we can just nest the condition into the $group, again this should not case
        // performance changes. also i switched the input to match with the inputs.
        $group: {
            _id: '$_id',
            inputs: {$sum: {$cond: {if: {$eq: ['$operation', 'input']}, then: '$product.quantity', else: 0}}},
            outputs: {$sum: {$cond: {if: {$eq: ['$operation', 'output']}, then: '$product.quantity', else: 0}}}
        }
    },
])

因此,回顾一下您的管道是最理想的,您怀疑与索引相关的问题在某种程度上是正确的。一旦你从第 3 部分构建了新索引,就会有相当大的性能变化。

需要考虑的是规模上升,您的数据库将(希望)继续增长。您当前的解决方案目前还不错,但最终它会在规模下塌陷,性能将再次下降。想到的 2 个简单选项是:

  1. 预处理,您所做的每次更新或插入都有一个预先计算的集合,该集合将使用这些操作进行更新并保存所需的指标。

  2. 创建一个“当前”集合以仅包含最近的数据并查询该数据。

这两个显然都会产生一些开销,您可以选择是否以及何时实施它们。


推荐阅读