全文搜索重量在猫鼬

Foa*_*ibi 46 full-text-search mongoose mongodb

据我所知,自3.8.9版以来,mongoose支持全文搜索.但我找不到一个好的文档!
我想做的事情如下:

db.collection.ensureIndex(
    // Fields to index
    {
        animal:  "text",
        color:   "text",
        pattern: "text",
        size:    "text"
    },

    // Options
    {
        name: "best_match_index",

        // Adjust field weights (default is 1)
        weights: {
            animal: 5,  // Most relevant search field
            size:   4   // Also relevant
       }
    }
)
Run Code Online (Sandbox Code Playgroud)

我可以用纯猫鼬做吗?或者我必须使用像mongoose-text-search这样的插件?没有重量怎么样?
我该怎么办呢?

eag*_*gor 109

是的,您可以在Mongoose中使用全文搜索> = 3.8.9.首先,一个集合最多可以有一个文本索引(参见docs).因此,要为多个字段定义文本索引,需要复合索引:

schema.index({ animal: 'text', color: 'text', pattern: 'text', size: 'text' });
Run Code Online (Sandbox Code Playgroud)

现在您可以使用$ text查询运算符,如下所示:

Model
    .find(
        { $text : { $search : "text to look for" } }, 
        { score : { $meta: "textScore" } }
    )
    .sort({ score : { $meta : 'textScore' } })
    .exec(function(err, results) {
        // callback
    });
Run Code Online (Sandbox Code Playgroud)

这也将按相关性分数对结果进行排序.

至于权重,你可以尝试将权重选项对象传递给index()方法(你定义复合索引)(至少使用mongoose的v4.0.1):

schema.index({ animal: 'text', color: 'text', pattern: 'text', size: 'text' }, {name: 'My text index', weights: {animal: 10, color: 4, pattern: 2, size: 1}});
Run Code Online (Sandbox Code Playgroud)

  • 返回错误:$ text查询只需要一个文本索引 (5认同)
  • 此过程是否记录在某处?我正在尝试将文本索引与猫鼬一起使用,但它不起作用。我创建了一个复合索引,我像您的示例一样使用了 $text 运算符,但结果始终是一个空文档。 (4认同)
  • 见[$ text doc](http://docs.mongodb.org/manual/reference/operator/query/text/#op._S_text)和[文本搜索教程](http://docs.mongodb.org/manual /管理/索引文本/).你的Mongoose版本是什么?(全文检索适用于ver> = 3.8.9) (2认同)
  • @Mallen你找到了解决方案吗? (2认同)