添加索引后,MongoDB的分组查询仍然很慢。

3

我有一个简单的集合:

{
    "_id" : ObjectId("5033cc15f31e20b76ca842c8"),
    "_class" : "com.pandu.model.alarm.Alarm",
    "serverName" : "CDCAWR009 Integration Service",
    "serverAddress" : "cdcawr009.na.convergys.com",
    "triggered" : ISODate("2012-01-28T05:09:03Z"),
    "componentName" : "IntegrationService",
    "summary" : "A device which is configured to be recorded is not being recorded.",
    "details" : "Extension<153; 40049> on CDCAWR009 is currently not being recorded
    properly; recording requested for the following reasons: ",
    "priority" : "Major"
}

这个集合中大约有数百万个这样的文档。我试图按服务器名称对它们进行分组,并获得所有服务器名称的计数。从关系型数据库查询的角度来看,这听起来很简单。

The query that I have come up with is 
    db.alarm.group( {key: { serverName:true }, reduce: function(obj,prev) { prev.count++ }, initial: { count: 0 }});

另外,我已经在serverName上添加了索引。

> db.alarm.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.alarm",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "serverName" : 1
                },
                "ns" : "test.alarm",
                "name" : "serverName_1"
        }
]

然而,在MongoDB中,我需要等待13秒才能得到响应。而在SQL Server中,类似的查询仅需4秒即可返回结果,且无须索引支持。
是否有遗漏了什么呢?
谢谢您的耐心等待。
2个回答

4
正如您所写的查询一样,2.0版本中这种聚合需要运行Map/Reduce。 MongoDB上的Map/Reduce存在一些性能损失,已经在SO before中进行了介绍 - 基本上,除非您能够跨集群并行处理,否则将通过Spidermonkey运行单线程JavaScript - 这不是一个高效的方案。由于您没有选择性,所以索引并没有真正帮助 - 您只需要扫描整个索引以及可能的文档。
然而,随着即将发布的2.2版本(目前正在rc1中),您有一些选择。在2.2中引入的聚合框架(原生的,不是基于JS的Map/Reduce)具有内置的group操作符,专门用于加速MongoDB中的这种操作。
我建议尝试使用2.2并查看分组性能是否有所改善。我认为它应该像这样:(注意:未经测试):
db.alarm.aggregate(
    { $group : {
        _id : "$serverName",
        count : { $sum : 1 }
    }}
);

让我试一下2.2。谢谢。 - nkare

2

帮我理解一下。如果在数据上运行distinct(),那么我会失去特定组中的实例数量;我正在寻找SQL世界中的“group by”功能。 - nkare
啊,抱歉。您可以遍历distinct()的元素,并为每个唯一的服务器名称运行.count()查询。该查询可以使用索引,并且您可以避免单线程Javascript。但是,我不确定这个解决方案是否比MR更好(取决于唯一名称的数量)。您最好的选择可能是新的聚合框架,但我很想看到基准数据。 - Jenna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接