芒果指数 "does not contain a valid index for this query" 即使手动指定

Mango index "does not contain a valid index for this query" even when specified manually

我正在尝试通过 Mango 高效地查询数据(因为这似乎是满足我的要求的唯一选择 Searching for sub-objects with a date range containing the queried date value),但我什至无法获得非常简单的 index/query 对工作:虽然我为查询手动指定了我的索引,但我被告知我的索引“未被使用,因为它不包含该查询的有效索引。没有找到匹配的索引,创建一个索引来优化查询时间。”

(我在 CouchDB v. 3.0.0 上通过 Fauxton 完成所有这些操作)

假设我的文档是这样的:

{
    "tenant": "TNNT_a",
    "$doctype": "JobOpening",
    // a bunch of other fields
}

所有 $doctype 为“JobOpening”的文档都保证有 tenant 属性。我希望执行的搜索将只针对带有 $doctype 的“JobOpening”的文档,并且在查询时将始终提供 tenant 选择器。

这是我配置的测试索引:

{
   "index": {
      "fields": [
          "tenant",
          "$doctype"
      ],
      "partial_filter_selector": {
        "\$doctype": {
          "$eq": "JobOpening"
        }
      }
   },
   "ddoc": "job-openings-doctype-index",
   "type": "json"
}

这是查询

{
   "selector": {
      "tenant": "TNNT_a",
      "\$doctype": "JobOpening"
   },
   "use_index": "job-openings-doctype-index"
}

为什么索引没有被用于查询?

我试过不使用部分索引,我认为 $doctype 转义在必要的地方正确完成,但似乎没有什么能阻止 CouchDB 执行完整扫描。

未使用索引,因为 $doctype 字段未按预期被查询计划程序识别。

将设计文档中的字段声明从 $doctype 更改为 \$doctype 即可解决问题。

{
   "index": {
      "fields": [
          "tenant",
          "\$doctype"
      ],
      "partial_filter_selector": {
        "\$doctype": {
          "$eq": "JobOpening"
        }
      }
   },
   "ddoc": "job-openings-doctype-index",
   "type": "json"
}

在那次小的重构之后,查询

    {
       "selector": {
          "tenant": "TNNT_a",
          "\$doctype": "JobOpening"
       },
       "use_index": "job-openings-doctype-index"
    }

Returns 预期结果,并生成一个“解释”,确认 job-openings-doctype-index 已被查询:

{
 "dbname": "stack",
 "index": {
  "ddoc": "_design/job-openings-doctype-index",
  "name": "7f5c5cea5acd90f11fffca3e3355b6a03677ad53",
  "type": "json",
  "def": {
   "fields": [
    {
     "tenant": "asc"
    },
    {
     "\$doctype": "asc"
    }
   ],
   "partial_filter_selector": {
    "\$doctype": {
     "$eq": "JobOpening"
    }
   }
  }
 },
// etc etc etc

尚不清楚此更改是否直观,但它是一致的 - 并且可能揭示带有“特殊”字符的前导字段名称可能并不可取。

关于筛选字段的索引,根据 documentation regarding partial_filter_selector

Technically, we don’t need to include the filter on the "status" [e.g. $doctype here] field in the query selector ‐ the partial index ensures this is always true - but including it makes the intent of the selector clearer and will make it easier to take advantage of future improvements to query planning (e.g. automatic selection of partial indexes).

尽管如此,我不会选择索引一个值是常量的字段。