带有索引的简单 Mongo 查找的高负载

如何解决带有索引的简单 Mongo 查找的高负载

我有一个 mongoDB,我正在使用 NodeJS(运行 mongoose)进行查询。

在这种特殊情况下,我正在查询一堆集合并将数据作为 CSV 传输到 archiverjs 以创建一个 zip 文件。所以我有一个传入请求,使用 mongoose 和 mongo 游标查询数据,通过管道输送到管道中,该管道将分别以 archiverjs 结束,http 响应将 zip 文件传送给用户。

async function getSortedQueryCursor(...) {
  ...

  const query = MODEL_LOOKUP[fileType]
    .find(reducer)
    .sort({ [idString]: 'asc' });

  return query.cursor();
}


async function getData(...) {
    const cursor = await getSortedQueryCursor(...);

    return cursor
      .pipe(filter1Stream)
      .pipe(filter2Stream)
      .pipe(filter3Stream)
      .pipe(csvStringifyStream);
}

router.post('/:scenarioId',async (request,response) => {
    ...

    const archive = Archiver(...);
    
    archive.pipe(response);

    const result = await getData(...);

    archive.append(stream,{ name: filepath });

    return archive.finalize();
}

只要某个特定集合在游戏中(该集合包含大约 4000 万个文档),查询就会持续很长时间(>15 秒),我可以看到在此期间 100% CPU 上的 mongo 进程。更令人惊讶的是结果集是空的(没有与查询匹配的文档)。

这是一个相当简单的查询:

items.find({ scenarioId: 'ckqf5ulg38gu208eecxlf95fc' },{ sort: { dataId: 1 }

我在 scenarioIddataId 上有索引。如果我在 shell 上运行查询,它会在 30ms 后返回。

explain() 导致:

[
  {
    "queryPlanner": {
      "plannerVersion": 1,"namespace": "data.items","indexFilterSet": false,"parsedQuery": {
        "scenarioId": {
          "$eq": "ckqf5ulg38gu208eecxlf95fc"
        }
      },"winningPlan": {
        "stage": "SORT","sortPattern": {
          "itemId": 1
        },"memLimit": 104857600,"type": "simple","inputStage": {
          "stage": "FETCH","inputStage": {
            "stage": "IXSCAN","keyPattern": {
              "scenarioId": 1
            },"indexName": "scenarioId_1","isMultiKey": false,"multiKeyPaths": {
              "scenarioId": []
            },"isUnique": false,"isSparse": false,"isPartial": false,"indexVersion": 2,"direction": "forward","indexBounds": {
              "scenarioId": [
                "[\"ckqf5ulg38gu208eecxlf95fc\",\"ckqf5ulg38gu208eecxlf95fc\"]"
              ]
            }
          }
        }
      },"rejectedPlans": [
        ...
      ]
    },"executionStats": {
      "executionSuccess": true,"nReturned": 0,"executionTimeMillis": 0,"totalKeysExamined": 0,"totalDocsExamined": 0,"executionStages": {
        "stage": "SORT","executionTimeMillisEstimate": 0,"works": 3,"advanced": 0,"needTime": 1,"needYield": 0,"saveState": 0,"restoreState": 0,"isEOF": 1,"sortPattern": {
          "dataId": 1
        },"totalDataSizeSorted": 0,"usedDisk": false,"works": 1,"needTime": 0,"docsExamined": 0,"alreadyHasObj": 0,\"ckqf5ulg38gu208eecxlf95fc\"]"
              ]
            },"keysExamined": 0,"seeks": 1,"dupsTested": 0,"dupsDropped": 0
          }
        }
      },...
    },"serverInfo": {
      ...
      "version": "4.4.6","gitVersion": "72e66213c2c3eab37d9358d5e78ad7f5c1d0d0d7"
    },...
  }
]

它告诉我(我在解释这些结果方面不是很有经验)查询非常便宜:"executionTimeMillisEstimate": 0, 因为它没有运行文档扫描 "docsExamined": 0,

接下来我连接到 mongo 服务器并运行 db.currentOp({"secs_running": {$gte: 5}}) 以从这边获取一些信息:

{
    "type" : "op",...
    "clientMetadata" : {
        "driver" : {
            "name" : "nodejs|Mongoose","version" : "3.6.5"
        },"os" : {
            "type" : "Linux","name" : "linux","architecture" : "x64","version" : "5.8.0-50-generic"
        },"platform" : "'Node.js v14.17.0,LE (unified)","version" : "3.6.5|5.12.3"
    },"active" : true,"secs_running" : NumberLong(16),"microsecs_running" : NumberLong(16661409),"op" : "query","ns" : "data.items","command" : {
        "find" : "items","filter" : {
            "scenarioId" : "ckqf5ulg38gu208eecxlf95fc"
        },"sort" : {
            "itemId" : 1
        },"projection" : {
            
        },"returnKey" : false,"showRecordId" : false,"lsid" : {
            "id" : UUID("be3ce18b-5365-4680-b734-543d06418301")
        },"$clusterTime" : {
            "clusterTime" : Timestamp(1625498044,1),"signature" : {
                "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),"keyId" : 0
            }
        },"$db" : "data","$readPreference" : {
            "mode" : "primaryPreferred"
        }
    },"numYields" : 14701,"locks" : {
        "ReplicationStateTransition" : "w","Global" : "r","Database" : "r","Collection" : "r"
    },"waitingForLock" : false,"lockStats" : {
        "ReplicationStateTransition" : {
            "acquireCount" : {
                "w" : NumberLong(14702)
            }
        },"Global" : {
            "acquireCount" : {
                "r" : NumberLong(14702)
            }
        },"Database" : {
            "acquireCount" : {
                "r" : NumberLong(14702)
            }
        },"Collection" : {
            "acquireCount" : {
                "r" : NumberLong(14702)
            }
        },"Mutex" : {
            "acquireCount" : {
                "r" : NumberLong(1)
            }
        }
    },"waitingForFlowControl" : false,"flowControlStats" : {
    }
}

任何想法如何提高性能或找到我的应用程序中的瓶颈?由于 mongo 方面的负载很高,并且没有找到/传递给应用程序的文件,我猜是 mongo 遇到了问题......

编辑:我已经使用 db.setProfilingLevel(2)db.system.profile.find().pretty() 从数据库端记录了整个过程。在这里我们可以看到整个集合(或者我误解了 "docsExamined" : 39612167?)被查询:

{
    "op" : "query","sort" : {
            "dataId" : 1
        },"projection" : {

        },...
        "$db" : "data","keysExamined" : 39612167,"docsExamined" : 39612167,"cursorExhausted" : true,"numYield" : 39613,"nreturned" : 0,"queryHash" : "B7F40289","planCacheKey" : "BADED068","locks" : {
        "ReplicationStateTransition" : {
            "acquireCount" : {
                "w" : NumberLong(39615)
            }
        },"Global" : {
            "acquireCount" : {
                "r" : NumberLong(39615)
            }
        },"Database" : {
            "acquireCount" : {
                "r" : NumberLong(39614)
            }
        },"Collection" : {
            "acquireCount" : {
                "r" : NumberLong(39614)
            }
        },"flowControl" : {

    },"storage" : {

    },"responseLength" : 242,"protocol" : "op_msg","millis" : 48401,"planSummary" : "IXSCAN { dataId: 1 }","execStats" : {
        "stage" : "CACHED_PLAN","nReturned" : 0,"executionTimeMillisEstimate" : 48401,"works" : 1,"advanced" : 0,"needTime" : 0,"needYield" : 0,"saveState" : 39613,"restoreState" : 39613,"isEOF" : 1,"inputStage" : {
            "stage" : "FETCH","filter" : {
                "scenarioId" : {
                    "$eq" : "ckqf5ulg38gu208eecxlf95fc"
                }
            },"executionTimeMillisEstimate" : 6270,"works" : 39612168,"needTime" : 39612167,"alreadyHasObj" : 0,"inputStage" : {
                "stage" : "IXSCAN","nReturned" : 39612167,"executionTimeMillisEstimate" : 2151,"advanced" : 39612167,"keyPattern" : {
                    "dataId" : 1
                },"indexName" : "dataId_1","isMultiKey" : false,"multiKeyPaths" : {
                    "dataId" : [ ]
                },"isUnique" : false,"isSparse" : false,"isPartial" : false,"indexVersion" : 2,"direction" : "forward","indexBounds" : {
                    "dataId" : [
                        "[MinKey,MaxKey]"
                    ]
                },"seeks" : 1,"dupsTested" : 0,"dupsDropped" : 0
            }
        }
    }

解决方法

(像往常一样)索引似乎没有正确设置。我创建了一个新的(二级?)索引:

{
    "dataId" : 1,"scenarioId": 1
}

现在查询在几毫秒内返回......

编辑:仍然让我感到疑惑的是,shell 查询以毫秒为单位返回,而 mongoose 查询花费了很长时间。尽管查询似乎相同(从我的角度来看)mongo 对它们的处理方式不同。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res