Control Search Results with Weights使用权重控制搜索结果

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.text索引,索引字段的权重表示该字段相对于其他索引字段在文本搜索分数方面的重要性。

For each indexed field in the document, MongoDB multiplies the number of matches by the weight and sums the results. 对于文档中的每个索引字段,MongoDB将匹配数乘以权重,并对结果求和。Using this sum, MongoDB then calculates the score for the document. 然后,使用这个总和,MongoDB计算文档的分数。See $meta operator for details on returning and sorting by text scores.有关按文本分数返回和排序的详细信息,请参阅$meta运算符。

The default weight is 1 for the indexed fields. 索引字段的默认权重为1。To adjust the weights for the indexed fields, include the weights option in the db.collection.createIndex() method.要调整索引字段的权重,请在db.collection.createIndex()方法中包含weight选项。

Warning

Choose the weights carefully in order to prevent the need to reindex.仔细选择重量,以免需要重新编制索引。

A collection blog has the following documents:集合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" ]
}

To create a text index with different field weights for the content field and the keywords field, include the weights option to the createIndex() method. 要为content字段和keywords字段创建具有不同字段权重的text索引,请在createIndex()方法中包含weight选项。For example, the following command creates an index on three fields and assigns weights to two of the fields:例如,以下命令在三个字段上创建索引,并为其中两个字段指定权重:

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

The text index has the following fields and weights:text索引具有以下字段和权重:

These weights denote the relative significance of the indexed fields to each other. 这些权重表示索引字段之间的相对重要性。For instance, a term match in the content field has:例如,content字段中的术语匹配有: