用猫鼬全重搜索重量 [英] Full text search with weight in mongoose

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

问题描述

据我所知,自3.8.9版本开始,猫鼬支持全文搜索。但是我无法找到一个好的文档!

我想做一些类似的事情:

  db.collection.ensureIndex(
//字段索引
{
动物:text,
颜色:text,
pattern:text,
size:text
},

//选项
{
名称:best_match_index,

/ /调整字段权重(默认值为1)
权重:{
animal:5,//最相关的搜索字段
size:4 //同样相关的
}
}

我可以用纯猫鼬做到吗?或者我必须使用一些插件,如猫鼬文本搜索?如果没有体重?

我应该怎么做? 是的,您可以使用全部在Mongoose的文本搜索> = 3.8.9。首先,一个集合最多只能有一个文本索引(请参阅文档)。因此,要为几个字段,您需要复合索引:


$ b

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

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

< pre-class =lang-js prettyprint-override> 模型
.find(
{$ text:{$ search:text to look for}},
{分数:{$ meta:textScore}}

.sort({分数:{$ meta:'textScore'}})
.exec(function(err,results ){
//回调
});

这也会按相关性分数对结果进行排序。



至于权重,您可以尝试将权重选项对象传递给 index() 方法(在这里定义复合索引)(至少在mongoose的v4.0.1中工作): <动态:'文本',颜色:'文本',模式:'文本',大小:'文本'},{名称:'我的文本索引',权重:{动物: 10,颜色:4,图案:2,尺寸:1}});


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

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?

解决方案

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

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.

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天全站免登陆