Sort operation used more than the maximum 33554432 bytes of RAM

在数据量超大的情形下,任何数据库系统在创建索引时都是一个耗时的大工程,下面这篇文章主要给大家介绍了关于MongoDB排序时内存大小限制与创建索引的注意事项的相关资料,需要的朋友可以参考下

线上服务的MongoDB中有一个很大的表,我查询时使用了sort()根据某个字段进行排序,结果报了下面这个错误:

[Error] Executor error during find command :: caused by :: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.
at line 0, column 0

这是个非常常见的MongoDB报错了。因为MongoDB处理排序时,如果排序的字段没有建立索引,会把全表都丢到内存中处理。

If MongoDB cannot use an index or indexes to obtain the sort order, MongoDB must perform a blocking sort operation on the data. A blocking sort indicates that MongoDB must consume and process all input documents to the sort before returning results.

而内存的大小并不是无限使用的,MongoDB的默认设置是32MB。一旦数据量超过32MB,则会报错。

参数internalQueryExecMaxBlockingSortBytes

32MB这个限制是在参数internalQueryExecMaxBlockingSortBytes中控制。你可以在MongoDB的客户端上直接查看这个参数的值,执行以下语句:

1
2
3
4
db.runCommand({
    getParameter: 1,
    "internalQueryExecMaxBlockingSortBytes": 1
})

返回如下结果:

// 1
{
    "internalQueryExecMaxBlockingSortBytes": NumberInt("33554432"),
    "ok": 1,
    "operationTime": Timestamp(1651142670, 1),
    "$clusterTime": {
        "clusterTime": Timestamp(1651142670, 1),
        "signature": {
            "hash": BinData(0, "X09M2FBji5f+FOwaK/nLTv4+Ybs="),
            "keyId": NumberLong("7080087363631710209")
        }
    }
}

所以解决排序时内存使用超过32MB的问题,有两个方法:

给排序的字段加索引。具体怎么加索引,会在后面细讲。

修改internalQueryExecMaxBlockingSortBytes参数的大小,使用命令如下:

1
2
3
4
db.adminCommand({
    setParameter: 1,
    internalQueryExecMaxBlockingSortBytes: 104857600
})

MongoDB 4.3的internalQueryMaxBlockingSortMemoryUsageBytes

我准备在本地的MongoDB上复现这个问题,于是把这个表直接导入到本地MongoDB中。结果发现排序时并没有报错。使用上面的命令查看internalQueryExecMaxBlockingSortBytes参数的值时,返回如下结果:

[17][ProtocolError] no option found to get

Google了一下,发现了MongoDB的官方网站上的两个相关JIRA。

第一个JIRA [SERVER-44053] Rename setParameter for maximum memory usage of blocking sort - MongoDB Jira里表示,在4.3.1版本时,因为参数命名描述不清楚,所以将参数internalQueryExecMaxBlockingSortBytes改为了internalQueryMaxBlockingSortMemoryUsageBytes。这解释了为什么我执行查询参数的语句时,没有返回结果。

第二个JIRA [SERVER-50767] internalQueryExecMaxBlockingSortBytes causing config exception on mongod load - Mongo中,Comments里提到了,新的internalQueryMaxBlockingSortMemoryUsageBytes参数,默认值从32MB改成了100MB。也许我的这个表使用100MB内存进行排序就够用了,所以没有报错。

 
posted @ 2022-11-02 00:27  野狼谷  阅读(494)  评论(0)    收藏  举报