gpt4 book ai didi

node.js - 如何加速 MongoDB count() 查询?

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:01 25 4
gpt4 key购买 nike

我的收藏描述如下:

{ "_id" : ObjectId("5474af69d4b28042fb63b856"), "name" : "XXXX", "action" : "accept", "source" : "127.0.0.1", "srcport" : "80", "destination" : "192.168.0.13", "dstport" : "53213", "service" : "443", "service_id" : "https", "unixtime" : NumberLong("1412774569000"), "segment" : "MySegment", "direction" : "INCOMING", "location" : "US" }

我的集合中目前有大约 5.5mio 条目,基本查询始终是:

collection.count({"action":"2_different_action_types", "direction":"3_different_directions", "unixtime": {"$gte": 1412774000000, "$lte": 1412774900000}})

Action、direction 和 unixtime 始终存在于我的查询中,但它们的值是动态的。可选(也是动态值)参数是:

  • 地点
  • 分割
  • service_id

例如:

collection.count({"action":"2_different_action_types", "direction":"3_different_directions", "location":"US","segment":"mySegment", "unixtime": {"$gte": 1412774000000, "$lte": 1412774900000}})
collection.count({"action":"2_different_action_types", "direction":"3_different_directions", "service_id":"https", "unixtime": {"$gte": 1412774000000, "$lte": 1412774500000}})

我创建了以下索引:

db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 })
db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 , location:1})
db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 , service_id:1})
db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 , segment:1})
db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 , location:1, service_id: 1})
db.collection.createIndex( {unixtime: 1, action: 1, direction: 1 , location:1, segment: 1})

我的没有索引的查询花了大约8秒,有索引的查询花了大约6秒,这仍然有点慢。

我怎样才能加快整个过程?请注意,目前我只是在计算结果,而不是真正寻找特定条目。

其他信息:

我目前正在尝试直接在 mongoshell 中优化这些查询,但最终,我通过 NodeJS 进行查询(不知道这是否与解决方案相关)。

最佳答案

这样的索引似乎没有多大意义。像 $gte$lte 这样的不等于查询应该位于末尾 - 不仅在查询中,而且在索引中。将 unixtime 放在索引中的位置 1 通常是一个坏主意(除非您需要在一秒内执行一组不同的操作,并且一秒内的操作数量如此之大以至于需要索引,但这是不可能的)。

尝试反转索引并确保索引的顺序与查询中的顺序匹配。

如果 locationsegmentservice_id 的选择性较低,请首先尝试在这些字段上不使用索引。更多索引会消耗更多 RAM,并且插入和更新时间会变慢,但由于选择性较低,查询的 yield 有时可以忽略不计。在查询中,将可选字段放在最后(所有其他操作的末尾)可能是有意义的 - 如果在所需条件和 unixtime 间隔之后候选集足够小,则进行集合扫描其余项目不会对性能造成太大影响。如果他们这样做并且选择性很高,请将他们进一步向前推进。

关于node.js - 如何加速 MongoDB count() 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27271225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com