MongoDB部分索引优化

问题描述 投票:0回答:1

我有一个 MongoDB 集合和以下查询:

{
  isActive: true,
  managerId: null,
  clientId: { $ne: null }
}

我想通过创建索引来优化这个查询。看起来部分索引将是一个很好的解决方案:

createIndex(
  { /** @todo: specify keys */ },
  {
    partialFilterExpression: {
      isActive: true,
      managerId: null,
      clientId: {
        $type: 'string',
      }
    }
  }
)

现在我知道要在

partialFilterExpression
中放入什么,但我不太清楚应该在“keys”属性中放入哪些字段。

我的查询到处都有固定的常量值,没有可变参数。

这种查询的最佳索引是什么?

mongodb mongodb-indexes
1个回答
0
投票

在研究了 @WernfriedDomscheit 的回应和一些实际实验后,我决定停止以下解决方案:

createIndex(
  {
    clientId: 1,
  },
  {
    partialFilterExpression: {
      isActive: true,
      managerId: null
    }
  }
);

说明:

  1. 正如@WernfriedDomscheit指出的,

    $type
    技巧对于
    clientId
    字段不起作用,因为查询规划器不会选择这样的索引来处理此查询(经实践证实)。

  2. 由于我无法使用

    clientId
    中的
    partialFilterExpression
    字段,我只是将其移至
    keys
    属性。这有效地解决了空键的问题。

正如我测试的那样,这个索引似乎非常适合我的查询。不过,如果您知道更优化的方法,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.