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)