创建通配符文本索引

您可以创建一个文本索引,其中包含集合中带有字符串数据的每个文档字段。这些文本索引称为通配符文本索引。通配符文本索引支持对未知、任意或动态生成的字段进行文本搜索。

要创建通配符文本索引,请将索引键设置为通配符说明符 ( $**) 并将索引值设置为text

db.<collection>.createIndex( { "$**": "text" } )

关于此任务

通配符文本索引与通配符索引不同。通配符文本索引支持使用$text运算符的查询,而通配符索引则不支持。

创建通配符文本索引后,当您插入或更新文档时,索引会更新以包含任何新的字符串字段值。因此,通配符文本索引会对插入和更新的性能产生负面影响。

仅当要索引的字段未知或可能更改时才使用通配符文本索引。通配符文本索引在特定字段上的性能不如目标文本索引。如果您的集合包含阻止目标索引的任意字段名称,请考虑重新建模您的架构以具有一致的字段名称。要了解有关目标索引的更多信息,请参阅创建索引以支持您的查询。

在你开始之前

创建blog包含以下文档的集合:

db.blog.insertMany( [
   {
     _id: 1,
     content: "This morning I had a cup of coffee.",
     about: "beverage",
     keywords: [ "coffee" ]
   },
   {
     _id: 2,
     content: "Who likes chocolate ice cream for dessert?",
     about: "food",
     keywords: [ "poll" ]
   },
   {
     _id: 3,
     content: "My favorite flavors are strawberry and coffee",
     about: "ice cream",
     keywords: [ "food", "dessert" ]
   }
] )

步骤

在集合上创建通配符文本索引blog

db.blog.createIndex( { "$**": "text" } )

结果

通配符文本索引支持对集合中所有字段进行文本搜索查询。考虑以下查询:

搜索单个单词

查询blog集合中的字符串coffee

db.blog.find( { $text: { $search: "coffee" } } )

输出:

[
  {
    _id: 1,
    content: 'This morning I had a cup of coffee.',
    about: 'beverage',
    keywords: [ 'coffee' ]
  },
  {
    _id: 3,
    content: 'My favorite flavors are strawberry and coffee',
    about: 'ice cream',
    keywords: [ 'food', 'dessert' ]
  }
]

前面的查询返回在任何字段中包含该字符串的所有文档 coffee

搜索多个术语

查询blog集合中包含字符串 poll 或 的 coffee文档:

db.blog.find( { $text: { $search: "poll coffee" } } )

输出:

[
  {
    _id: 1,
    content: 'This morning I had a cup of coffee.',
    about: 'beverage',
    keywords: [ 'coffee' ]
  },
  {
    _id: 3,
    content: 'My favorite flavors are strawberry and coffee',
    about: 'ice cream',
    keywords: [ 'food', 'dessert' ]
  },
  {
    _id: 2,
    content: 'Who likes chocolate ice cream for dessert?',
    about: 'food',
    keywords: [ 'poll' ]
  }
]

前面的查询返回包含该字符串pollcoffee任何字段的文档。

搜索准确的短语

查询blog集合中包含短语的文档 chocolate ice cream

db.blog.find( { $text: { $search: "\"chocolate ice cream\"" } } )

输出:

[
  {
    _id: 2,
    content: 'Who likes chocolate ice cream for dessert?',
    about: 'food',
    keywords: [ 'poll' ]
  }
]

前面的查询返回在任何字段中包含确切短语的文档 chocolate ice cream

了解更多

Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2023-09-01 17:10:26

results matching ""

    No results matching ""