mongodb - $exists : true (sparse indexes) 的最佳复合索引

标签 mongodb mongodb-query

问题

我需要加速这种查询:

db.col.find({ a: "foobar", b: { $exists: true} });

数据分布

字段的存在:

  • 字段a存在于所有文档中,
  • b 字段仅存在于其中的约 10%。

当前表统计:

db.col.count() // 1,050,505
db.col.count({ a : "foobar" }) // 517.967
db.col.count({ a : "foobar", b : { $exists: true} }) // 44.922
db.col.count({ b : { $exists: true} }) // 88.981

future 的数据增长:

到目前为止,已加载两批(2 倍,约 500,000)。 每个月都会添加另一批约 500,000 份文件。 a 字段是该批处理的名称。这些新添加的文档将具有相同的字段分布(大约 10% 的新加载文档将具有 b 字段)

我的尝试和研究

我在 {a:1, b:1} 上创建了一个稀疏索引,但是因为 a 出现在所有文档中,所以这并没有加快它的速度。那是因为 MongoDB 中稀疏索引的行为。来自docs :

Sparse compound indexes that only contain ascending/descending index keys will index a document as long as the document contains at least one of the keys.

这是上层查询的.explain():

{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "myCol",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "$and" : [ 
                {
                    "a" : {
                        "$eq" : "foobar"
                    }
                }, 
                {
                    "b" : {
                        "$exists" : true
                    }
                }
            ]
        },
        "winningPlan" : {
            "stage" : "KEEP_MUTATIONS",
            "inputStage" : {
                "stage" : "FETCH",
                "filter" : {
                    "b" : {
                        "$exists" : true
                    }
                },
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "keyPattern" : {
                        "a" : 1,
                        "b" : 1
                    },
                    "indexName" : "a_1_b_1",
                    "isMultiKey" : false,
                    "direction" : "forward",
                    "indexBounds" : {
                        "a" : [ 
                            "[\"foobar\", \"foobar\"]"
                        ],
                        "b" : [ 
                            "[MinKey, MaxKey]"
                        ]
                    }
                }
            }
        },
        "rejectedPlans" : []
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 44922,
        "executionTimeMillis" : 208656,
        "totalKeysExamined" : 517967,
        "totalDocsExamined" : 517967,
        "executionStages" : {
            "stage" : "KEEP_MUTATIONS",
            "nReturned" : 44922,
            "executionTimeMillisEstimate" : 180672,
            "works" : 550772,
            "advanced" : 44922,
            "needTime" : 473045,
            "needFetch" : 32804,
            "saveState" : 41051,
            "restoreState" : 41051,
            "isEOF" : 1,
            "invalidates" : 0,
            "inputStage" : {
                "stage" : "FETCH",
                "filter" : {
                    "b" : {
                        "$exists" : true
                    }
                },
                "nReturned" : 44922,
                "executionTimeMillisEstimate" : 180612,
                "works" : 550772,
                "advanced" : 44922,
                "needTime" : 473045,
                "needFetch" : 32804,
                "saveState" : 41051,
                "restoreState" : 41051,
                "isEOF" : 1,
                "invalidates" : 0,
                "docsExamined" : 517967,
                "alreadyHasObj" : 0,
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "nReturned" : 517967,
                    "executionTimeMillisEstimate" : 3035,
                    "works" : 517967,
                    "advanced" : 517967,
                    "needTime" : 0,
                    "needFetch" : 0,
                    "saveState" : 41051,
                    "restoreState" : 41051,
                    "isEOF" : 1,
                    "invalidates" : 0,
                    "keyPattern" : {
                        "a" : 1,
                        "b" : 1
                    },
                    "indexName" : "a_1_b_1",
                    "isMultiKey" : false,
                    "direction" : "forward",
                    "indexBounds" : {
                        "a" : [ 
                            "[\"foobar\", \"foobar\"]"
                        ],
                        "b" : [ 
                            "[MinKey, MaxKey]"
                        ]
                    },
                    "keysExamined" : 517967, // INFO: I think that this is too much. These are all documents having a:"foobar"
                    "dupsTested" : 0,
                    "dupsDropped" : 0,
                    "seenInvalidated" : 0,
                    "matchTested" : 0
                }
            }
        },
        "allPlansExecution" : []
    },
    "serverInfo" : {
        "host" : "productive-mongodb-16",
        "port" : 27000,
        "version" : "3.0.1",
        "gitVersion" : "534b5a3f9d10f00cd27737fbcd951032248b5952"
    }
}

a 存在于所有 1,000,000 个文档中,其中 520,000 个具有 a:"foobar"。在整个集合中有 88,000 个具有 b 字段。

如何加速我的查询(以便 IXSCAN 仅返回 44k 而不是 520k)?

最佳答案

你在这里似乎没有理解的是 $exists不能以任何方式“抓取”索引,即使在稀疏的地方也是如此。 正如文档本身所说:

"If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index"

这些页面中给出的示例是一个 { "$exists": false } 查询。但是相反的逻辑条件在这里没有任何区别。

为了获得“稀疏”索引的“全部好处”,您需要考虑它保存的数据的“类型”并进行适当的查询。

对于数字,类似于:

db.collection.find({ "a": "foobar", "b": { "$gte": -9999, "$lte": 9999 } })

它使用索引,而且是稀疏索引。或者对于基于文本的:

db.collection.find({ "a": "foobar", "b": /.+/ })

这也将使用稀疏索引并且只查看那些定义了“b”的索引。

对于“数组”,则“小心”。由于正在查看的值可能是上述值之一,除非您这样做:

db.collection.insert({ "a": 1, "b": [[]] })

哪里可以呢:

db.ab.find({ "a": 1, "b": { "$type": 4 } })

但由于同样的原因 $exists 在这里不起作用,也不会真的使用“稀疏”索引。

因此,如果您希望获得最佳性能,您需要了解这些术语的含义,并“适本地查询”以便使用您创建的索引定义。

这些是您可以自己测试并查看结果是否真实的清晰示例。我确实希望核心文档在这些方面更加清晰,但我也知道许多人已经尝试做出贡献(并做出了很好的解释),但迄今为止这些都没有包含在内。

我猜这就是你在这里问的原因。

关于mongodb - $exists : true (sparse indexes) 的最佳复合索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31340290/

相关文章:

c# - 如何在数组.NET驱动程序中的项目属性上创建MongoDB MultiKey索引

mongodb - 如何使用锁定文档运行 MongoDB 查询以供以后更新?

mongodb - 如何在mongo聚合中将数字转换为月份

javascript - 查询 MongoDB,用正则表达式替换一个特定字段

mongodb - 投影使查询变慢

使用嵌入文档作为键的 MongoDB 查询

javascript - Meteor:如何将项目推送到用户集合并创建列表或数组,而不是用新项目替换每个项目?

在 Ubuntu 14.04 中安装 MongoDB 失败

node.js - Mongodb 更新所有具有唯一 id 的文档

php - 如何在mongodb中找到数组的最后一项?