翻译或纠错本页面

通过权重控制搜索结果

Text search assigns a score to each document that contains the search term in the indexed fields. The score determines the relevance of a document to a given search query.

For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score.

For each indexed field in the document, MongoDB multiplies the number of matches by the weight and sums the results. Using this sum, MongoDB then calculates the score for the document. See $meta operator for details on returning and sorting by text scores.

键的默认权重是1.如果希望调整键的权重,可以在 db.collection.ensureIndex() 方法中添加 weights 选项。

警告

慎重选择权重,以免重新索引

集合 blog 有如下文档:

{
  _id: 1,
  content: "This morning I had a cup of coffee.",
  about: "beverage",
  keywords: [ "coffee" ]
}

{
  _id: 2,
  content: "Who doesn't like cake?",
  about: "food",
  keywords: [ "cake", "food", "dessert" ]
}

为了创建一个文本索引且 content 和 keywords`` 键有不同的权重,可以在 ensureIndex() 方法中包含 weights 选项。例如,如下命令会创建一个有三个键的索引并给两个键赋予权重:

db.blog.createIndex(
   {
     content: "text",
     keywords: "text",
     about: "text"
   },
   {
     weights: {
       content: 10,
       keywords: 5
     },
     name: "TextIndex"
   }
 )

这个 文本 索引有如下键和权重:

  • content 的权重为 10,

  • keywords 的权重为5,

  • about 的权重为默认值1。

这些权重表面了这些键互相之间的相对重要性。例如,在 content 键中匹配的单词:

  • 它的重要性会是在 keywords 键中得到匹配的单词的重要性的 两倍 ( 10:5 )

  • 10 times (i.e. 10:1) the impact as a term match in the about field.