【发布时间】:2019-07-30 05:30:14
【问题描述】:
我有一个托管 250+ 百万个文档的 MongoDB 分片集群。
文档结构如下:
{
"app_id": "whatever",
"created": ISODate("2018-05-06T12:13:45.000Z"),
"latest_transaction": ISODate("2019-03-06T11:11:40.000Z"),
"anotherField1": "Str", "anotherField2": "Str", ...otherfields
}
{
"app_id": "whatever",
"created": ISODate("2018-04-06T12:13:45.000Z"),
"latest_transaction": ISODate("2019-03-06T11:11:40.000Z"),
"uninstalled": ISODate("2019-03-07T11:11:40.000Z"),
"anotherField1": "Str", "anotherField2": "Str", ...otherfields
}
所以基本上有些文档有字段uninstalled,有些则没有。
以下是对集合的查询(是pymongo的解释,对不起datetime.datetime):
{
'$and': [
{'app_id': {'$eq': 'whatever'}},
{'created': {'$lt': datetime.datetime(2019, 3, 7, 0, 0)}},
{'latest_transaction': {'$gt': datetime.datetime(2019, 2, 5, 0, 0)}},
{'$nor': [{'uninstalled': {'$lt': datetime.datetime(2019, 3, 7, 0, 0)}}]}
]
}
这是我收藏的两个相关索引:
Index1: {"created": 1, "latest_transaction": -1, "uninstalled": -1, "app_id": 1}
Index2: {'app_id': 1, 'anotherField1': 1, 'anotherField2': 1}
现在的问题是,MongoDb 查询规划器似乎永远不会选择我在集合中拥有的 Index1 用于完全相同的目的!
我最初的印象是查询将使用一个覆盖索引和我构建索引的方式[因此,非常快],但对我来说很奇怪,mongodb 正在使用 Index2 并且一切都太慢了,有时需要 10 分钟以上,对于 150 万个文档的结果集通常需要大约 6 分钟 [即匹配的 app_id 大约有 150 万个文档]。
这里是查询的解释输出,显示 rejected 计划使用“Index1”
{
'inputStage': {
'inputStage': {
'direction': 'forward',
'indexBounds': {
'app_id': ['["whatever", "whatever"]'],
'created': ['(true, new Date(1551916800000))'],
'latest_transaction': ['[new Date(9223372036854775807), new Date(1549324800000))'],
'uninstalled': ['[MaxKey, new Date(1551916800000)]', '[true, MinKey]']
},
'indexName': 'created_1_latest_transaction_-1_uninstalled_-1_app_id_1',
'indexVersion': 2,
'isMultiKey': False,
'isPartial': False,
'isSparse': False,
'isUnique': False,
'keyPattern': {
'app_id': 1.0,
'created': 1.0,
'latest_transaction': -1.0,
'uninstalled': -1.0
},
'multiKeyPaths': {'app_id': [], 'created': [], 'latest_transaction': [], 'uninstalled': []},
'stage': 'IXSCAN'},
'stage': 'FETCH'},
'stage': 'SHARDING_FILTER'
}
以下是使用无关的、未发现的、Index2的获胜计划:
{'inputStage': {
'inputStage': {'direction': 'forward',
'indexBounds': {
'app_id': ['["whatever", "whatever"]'],
'anotherField1': ['[MinKey, MaxKey]'],
'anotherField2': ['[MinKey, MaxKey]']},
'indexName': 'app_id_1_anotherField2_1_anotherField1_1',
'indexVersion': 2,
'isMultiKey': False,
'isPartial': False,
'isSparse': False,
'isUnique': False,
'keyPattern': {'app_id': 1, 'anotherField1': 1, 'anotherField2': 1},
'multiKeyPaths': {'app_id': [], 'anotherField1': [], 'anotherField2': []},
'stage': 'IXSCAN'},
'stage': 'FETCH'},
'stage': 'SHARDING_FILTER'
}
- 关于为什么 mongodb 不能正确使用我的索引的任何想法?
- 是因为 uninstalled 可能不存在于某些文档中吗?
- 做复合日期时指数方向的一些解释
查询也将不胜感激,也许原因是
索引方向?
(1, -1, -1, 1)
谢谢! :)
------------ 编辑 --------------
解释的完整结果有点长,所以我把它粘贴了here,它解释了 queryPlanner 选择的索引 (Index2)。
还有关于 shard_key,它与这里查询的完全不同,这就是为什么我只为这个查询定义一个单独的特定索引。 (分片键是 (app_id, android_id, some_other_field_not_in_query) 上的复合索引。
【问题讨论】:
标签: mongodb performance indexing pymongo query-planner