【发布时间】:2019-06-05 00:49:17
【问题描述】:
我在使用 NodeJS+Express+MongoDB 开发的 API 上遇到性能问题。
在特定产品上使用 $match 运行聚合时,性能很好,但对于开放式搜索,它真的很慢。
我想在两个列上运行一个组:国家和出口商,然后在国家/地区获取限制为每组 3 个结果的结果。
要求:沿线每个国家/地区的唯一出口商总数 每个国家/地区的任意 3 条记录。
在我的aggregate function 上运行explain() 时,我收到以下关键指针,这些指针表明我的查询速度很慢。如果我错了,请纠正我。
"indexFilterSet": false-
"winningPlan": {"stage": "COLLSCAN","direction": "forward"},
对9,264,947 记录运行查询,所用时间约为32 seconds。
我尝试过使用复合索引和单字段索引,但它根本没有帮助,因为我觉得索引没有被使用 $match 为空 {}
下面是我使用 mongoose 驱动程序在 mongoDB 上运行的查询
Model.aggregate([
{"$match" : query},
{ $group : {_id: {country: "$Country", exporter: "$Exporter"}, id: {$first: "$_id"}, product: { $first: "$Description" }}},
{ $group : {_id: "$_id.country", data: {$push: { id: "$id", company: "$_id.exporter", product: "$product" }}, count:{$sum:1}}},
{ "$sort": { "count": -1 } },
{
$project: {
"data": { "$slice": [ "$data", 3 ] },
"_id": 1,
"count": 1
}
},
]).allowDiskUse(true).explain()
其中,query 是动态构建的,默认情况下为空 {} 用于集合范围的搜索。
索引字段是
复合索引:
{Country: 1, Exporter: 1}文字索引:
{Description: "text"}
完整的解释()响应:
{
"success": "Successfull",
"status": 200,
"data": {
"stages": [
{
"$cursor": {
"query": {},
"fields": {
"Country": 1,
"Description": 1,
"Exporter": 1,
"_id": 1
},
"queryPlanner": {
"plannerVersion": 1,
"namespace": "db.OpenExportData",
"indexFilterSet": false,
"parsedQuery": {},
"winningPlan": {
"stage": "COLLSCAN",
"direction": "forward"
},
"rejectedPlans": []
}
}
},
{
"$group": {
"_id": {
"country": "$Country",
"exporter": "$Exporter"
},
"id": {
"$first": "$_id"
},
"product": {
"$first": "$Description"
}
}
},
{
"$group": {
"_id": "$_id.country",
"data": {
"$push": {
"id": "$id",
"company": "$_id.exporter",
"product": "$product"
}
},
"count": {
"$sum": {
"$const": 1
}
}
}
},
{
"$sort": {
"sortKey": {
"count": -1
}
}
},
{
"$project": {
"_id": true,
"count": true,
"data": {
"$slice": [
"$data",
{
"$const": 3
}
]
}
}
}
],
"ok": 1
}
}
集合大小:9,264,947 条记录和 10.2 GB
响应时间:32154 毫秒
随着我的集合大小的增加,查询变得越来越慢。
【问题讨论】:
标签: node.js mongodb mongoose aggregate