限制扫描条目的数量

    本教程描述了如何创建索引来限制对包含$text表达式和相等条件的查询扫描的索引条目的数量。

    集合inventory包含以下文档:

    1. { _id: 1, dept: "tech", description: "lime green computer" }
    2. { _id: 2, dept: "tech", description: "wireless red mouse" }
    3. { _id: 3, dept: "kitchen", description: "green placemat" }
    4. { _id: 4, dept: "kitchen", description: "red peeler" }
    5. { _id: 5, dept: "food", description: "green apple" }
    6. { _id: 6, dept: "food", description: "red potato" }

    考虑由各个部门执行文本搜索的通用用例,例如:

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

    为了限制文本搜索只扫描特定部门内的那些文档,创建一个复合索引,首先在字段dept上指定一个升序/降序索引键,然后在字段描述上指定一个文本索引键:

    1. db.inventory.createIndex(
    2. {
    3. dept: 1,
    4. description: "text"
    5. }
    6. )

    然后,特定部门内的文本搜索将限制索引文档的扫描。例如,下面的查询只扫描那些dept = kitchen的文档:

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

    [success] 注意

    • 复合text索引不能包含任何其他特殊索引类型,例如多键地理空间索引字段。

    • 如果复合text索引在 索引键之前包含键,则要text执行$text搜索,查询谓词必须在前面的键上包含相等匹配条件

    • 创建复合text索引时,所有text索引键必须在索引规范文档中相邻列出。

    也可以看看

    文字索引

    译者:杨帅