【问题标题】:MongoDB optimal Index | Query planner behaviorMongoDB 最优索引 |查询规划器行为
【发布时间】: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


    【解决方案1】:

    在这里回答我自己的问题,

    MongoDB 的查询计划器分数现在似乎已重新调整,它们现在反映了与所有查找谓词匹配的索引的更高值。

    所以基本上,它需要几个小时的时间来确定Index1: {"created": 1, "latest_transaction": -1, "uninstalled": -1, "app_id": 1} 应该比其他指数有更高的分数,而我预计行为的变化会立即发生。

    计划者的分配分数和当前评估也是can be accessed in Mongodb,以下命令帮助我弄清楚分数以及它们如何随着时间的推移而进步。

    var queryShape = db.installation.getPlanCache().listQueryShapes()[IDX]
    db.installation.getPlanCache().getPlansByQuery(queryShape)
    

    【讨论】:

      【解决方案2】:

      涵盖的查询需要正确的投影 - 请确保您要求仅返回索引中的字段。特别是对于分片集合,索引还应该包含分片键:https://docs.mongodb.com/manual/core/query-optimization/#restrictions-on-sharded-collection

      您可以使用allPlansExecution 参数从explain 获取更多详细信息。它将向您展示规划器如何运行样本以及 index2 获胜的原因。

      https://github.com/mongodb/mongo/blob/master/src/mongo/db/query/plan_ranker.cpp#L191是分数的计算方式:

      baseScore = 1
      productivity = advanced / works // the main one 
      
      tieBreak = very_small_number
         + noFetchBonus // 0 for not covered queries
         + noSortBonus // 0 for no sort
         + noIxisectBonus // 0 for index intersection
      
      score = baseScore + productivity + tieBreakers
      
      

      它会在返回的前 100 个文档(高级)中选择得分较高的计划,这通常可以很好地了解它将如何用于整个查询。如果您对此表示怀疑,请尝试hint 另一个索引并检查它是否更快。

      更新

      shard key 是 (app_id, android_id, some_other_field_not_in_query) 上的复合索引

      有点解释它。 app_id 是 sharding key 和 Index2 中的公共前缀。这意味着使用这个索引 mongo 可以立即决定要查询哪些分片。 更改 Index1 中字段的顺序以匹配分片键前缀:

      Index1: {"app_id": 1, "created": 1, "latest_transaction": -1, "uninstalled": -1}
      

      解释中的基本数字:

         u'inputStage': {u'advanced': 0,
           u'indexName': u'created_1_latest_transaction_-1_uninstalled_-1_app_id_1',       
      
      
         u'inputStage': {u'advanced': 88,
           u'indexName': u'app_id_1_is_enabled_1_another_id_1',
      
         u'inputStage': {u'advanced': 12,
           u'indexName': u'app_id_1_uninstalled_1_is_enabled_1',
      
         u'inputStage': {u'advanced': 101,
           u'indexName': u'app_id_1_is_enabled_1_gaid_1',
      

      获胜者是app_id_1_is_enabled_1_gaid_1,因为它在评估期间成功返回了 101 个文档。没有匹配前缀 created_1_latest_transaction_-1_uninstalled_-1_app_id_1 的至少慢了 100 倍。

      【讨论】:

      • 感谢您的信息。实际上我并不真正关心被覆盖的查询。我只是希望它与我已经拥有的“所有查询字段”的索引相匹配!为什么那行不通?我有一个涵盖该查询中所有字段的复合索引,为什么不使用该索引?指数方向错了吗?或者像 $nor 查询不会使用索引?有什么想法吗?
      • 嗯,我怀疑我能否让“它选择得分更高的计划”这句话更清楚。如果您提供缺少的详细信息,我可以用确切的数字更新答案。请包括完整的查询(投影、排序等)、分片键索引、带有 allPlansExecution 参数的解释结果。仅当您进行排序时,方向才重要。如果不排序,复合索引中的字段顺序更重要。如果您不关心为什么而只想使用其他索引 - 使用提示强制它。
      • 我已在编辑中提供了您想要的信息。基本上没有种类,我想知道也没有投影的情况。解释也适用于简单的find(query).explain()。有趣的是,如果没有排序,方向根本不重要!谢谢,不知道。如果你能看一下解释,看看你能不能帮我解决这个问题,我会很高兴:) 再次感谢
      • 嗯,嗯,shard_key 是复合的(有 2 个其他字段),我总共有 4 个分片,所以很可能,mongodb 无论如何都必须查询所有分片。我不明白的是每个分片中查询的性能,因为既然您无论如何都必须查询所有分片,为什么不使用匹配所有过滤字段的更好的索引呢?我误解了什么吗? (我基本上不同意 app_id 作为 shard_key 前缀,因此它提高了查询性能,依赖于它无论如何都是分散聚集的想法)
      • 好吧,find(query).explain() 不是很有用。我在问find(query).explain("allPlansExecution"),但我想这已经没有必要了。我已经用关于分片键的解释更新了答案。具有较长匹配前缀的索引将始终获胜。当然,没有必要谈论涵盖的查询。这样的分片键不会发生这种情况。
      猜你喜欢
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      相关资源
      最近更新 更多