猫鼬中的权重全文搜索 [英] Full text search with weight in mongoose

查看:31
本文介绍了猫鼬中的权重全文搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,从 3.8.9 版本开始,猫鼬支持全文搜索.但我找不到合适的文档!
我想做类似的事情:

As I find out, since version 3.8.9, mongoose support full text search. But I can't find a good documentation for it!
I want to do something like:

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
       }
    }
)

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

Can I do it with pure mongoose? Or I have to use some plugin like mongoose-text-search? How about without weight?
And how should I do it?

推荐答案

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

Yes, you can use full text search in Mongoose >= 3.8.9. Firstly, a collection can have at most one text index (see docs). So, to define text index for several fields, you need compound index:

schema.index({ animal: 'text', color: 'text', pattern: 'text', size: 'text' });

现在您可以使用 $text 查询运算符 像这样:

Now you can use $text query operator like this:

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

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

This will also sort results by relevance score.

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

As for weights, you can try to pass weights options object to index() method (where you define compound index) (working at least with v4.0.1 of mongoose):

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

这篇关于猫鼬中的权重全文搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆