文档菜单
文档首页
/
MongoDB 手册
/ / /

在自托管部署中限制扫描的文本索引条目数量

本页内容

  • 关于此任务
  • 步骤
  • 结果
  • 查看检查的文档数量
  • 了解更多

如果您在大型数据集上执行文本搜索查询,单字段文本索引可能需要扫描大量条目以返回结果,这可能导致查询缓慢。

为了提高查询性能,您可以创建一个复合文本索引 并在文本搜索查询中包含一个相等匹配。如果复合索引包含您相等匹配中使用的字段,索引扫描的条目更少,返回结果更快。

在这个例子中,一位店长查询了一个库存 集合,该集合包含以下文档

db.inventory.insertMany( [
{ _id: 1, department: "tech", description: "lime green computer" },
{ _id: 2, department: "tech", description: "wireless red mouse" },
{ _id: 3, department: "kitchen", description: "green placemat" },
{ _id: 4, department: "kitchen", description: "red peeler" },
{ _id: 5, department: "food", description: "green apple" },
{ _id: 6, department: "food", description: "red potato" }
] )

店长针对特定部门的商品执行文本搜索查询。

departmentdescription 字段上的复合文本索引限制了索引键的扫描范围,仅限于指定的 department 中的文档。与在 description 字段上的单字段文本索引相比,复合文本索引提供了更好的性能。

在包含以下字段的 inventory 集合上创建一个组合索引

  • department 字段上的升序或降序索引键

  • description 字段上的 text 索引键

db.inventory.createIndex(
{
department: 1,
description: "text"
}
)

创建组合索引后,文本搜索查询仅扫描与指定等于条件的 department 字段匹配的文档。

例如,以下查询扫描与 department 等于 kitchen 的文档,其中 description 字段包含字符串 green

db.inventory.find( { department: "kitchen", $text: { $search: "green" } } )

输出

[ { _id: 3, department: 'kitchen', description: 'green placemat' } ]

要查看查询返回所需的文档数量,请查看查询的 executionStats:

db.inventory.find(
{
department: "kitchen", $text: { $search: "green" }
}
).explain("executionStats")

检查的索引键数量在totalKeysExamined字段中指示。检查更多索引键的查询通常需要更长时间才能完成。

departmentdescription上的复合索引中,查询只检查一个索引键。集合中只有一个文档,其中department字段为kitchen,且description字段包含字符串green

但是,如果查询只使用在description字段上的单字段文本索引,则查询将检查三个索引键。集合中有三个文档,其中description字段包含字符串green

在前面示例中使用的小集合中,单字段文本索引和复合文本索引之间的性能差异并不明显。然而,在较大的集合中,增加的索引条目扫描可能会明显影响性能。为了获得最佳性能,创建文本索引,以将索引条目的扫描数量限制在最适合您的等式匹配。

返回

分配权重

© . All rights reserved.