Fernando 你错了,它匹配GESCO CONSORZIO AGRICOLA WRONG,但它只匹配你搜索的一个词(标记)consorzio 而不是la。
在文本搜索中textScore 将大于 1
匹配查询的所有标记。
例如这里是一个商店集合
db.stores.insert(
[
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Java Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods" },
{ _id: 6, name: "Java Hut", description: "Coffee and cakes" }
]
)
索引
db.stores.createIndex( { name: "text" } )
现在如果我查询
db.stores.find({
$text: {
$search: "Java Shop"
}
}, {
score: {
$meta: "textScore"
}
}).sort({
score: {
$meta: "textScore"
},
_id: -1
})
它将匹配令牌,结果是
/* 1 */
{
"_id" : 6.0,
"name" : "Java Shopping",
"description" : "Indonesian goods",
"score" : 1.5
}
/* 2 */
{
"_id" : 5.0,
"name" : "Java Shopping",
"description" : "Indonesian goods",
"score" : 1.5
}
/* 3 */
{
"_id" : 3.0,
"name" : "Java Coffee Shop",
"description" : "Just coffee",
"score" : 1.33333333333333
}
/* 4 */
{
"_id" : 1.0,
"name" : "Java Hut",
"description" : "Coffee and cakes",
"score" : 0.75
}
在这里您可以看到前三个文档匹配所有标记,这就是为什么 score 大于 1 而最后一个文档 score 小于 1 因为它只匹配一个标记。
现在,在得分大于 1 的情况下,您还可以获得匹配所有标记的最佳文档。为此,我们需要使用 MongoDB Aggregation。
db.stores.aggregate([
{
"$match": {
"$text": {
"$search": "Java Shop"
}
}
},
{
"$addFields": {
"score": {
"$meta": "textScore"
}
}
},
{
"$match": {
"score": { "$gt": 1.0 }
}
},
{
"$sort": {
"score": -1, _id: -1
}
},
{
"$limit": 1
}
])
&这里是结果
/* 1 */
{
"_id" : 6.0,
"name" : "Java Shopping",
"description" : "Indonesian goods",
"score" : 1.5
}