我在应用程序中使用mongo文本搜索。
索引:
db.test.createIndex(
{
title: 'text',
description: 'text'
},
{
name: "TextIndex",
weights: {
title: 10,
description: 1
}
}
)得分:
title : 10
description : 1文件:
db.test.insert(
[
{ _id: 1, title: "agent de production", description: "production or agent"},
{ _id: 2, title: "agent test production", description: "agent" },
{ _id: 3, title: "production agent", "description" : "production"},
{ _id: 4, title: "agent", "description" : "production"},
{ _id: 5, title: "test", "description" : "production example agent"},
]
)问题
所以如果我搜索“代理生产”
结果应该是
[
{ _id: 1, title: "agent de production", description: "production or agent"},
{ _id: 2, title: "agent test production", description: "agent" },
{ _id: 3, title: "production agent", "description" : "production"},
{ _id: 5, title: "test", "description" : "production example agent"},
]我试过的是:
db.test.find({"$text" : {"$search" : "\"agent production\""}}); Query result does not match with the expected result.结果:0
查询短语:db.test.find({"$text“:{"$search”:“\”代理\“生产\”})
结果:
{ "_id" : 5, "title" : "test", "description" : "production example agent" }
{ "_id" : 1, "title" : "agent de production", "description" : "production or agent" }
{ "_id" : 3, "title" : "production agent", "description" : "production" }
{ "_id" : 2, "title" : "agent test production", "description" : "agent" }
{ "_id" : 4, "title" : "agent", "description" : "production" }任何建议都将不胜感激。
发布于 2016-02-18 06:08:30
让我们回顾一下$search查询中的$text字符串是如何工作的。如果给出一个短语,就像在"$search": "\"agent production\""中一样,只有与短语匹配的索引字段的文档才能获得非零分数。这就解释了为什么在这种情况下没有发现结果。但是,指定"$search": "\"production agent\""将使文档与_id: 3匹配。如果给出了单独的单词/术语,如在"$search": "\"agent\" \"production\""中,任何带有索引字段的文档都会得到分数。这解释了为什么返回带有_id: 4的文档,因为它在单个字段中不一定同时包含两个术语,正如您在期望的结果中所显示的那样。
要强制两个搜索项都包含在单个字段中,您需要向查询中添加其他子句。您可以执行文本搜索以对文档进行评分,并使用regex进一步过滤文档,如下所示:
db.test.find( { $and: [ { "$text": { "$search": "\"agent\" \"production\"" } },
{ $or: [
{ $and: [ { title: /agent/i }, { title: /production/i } ] },
{ $and: [ { description: /agent/i }, { description: /production/i } ] }
] }
] }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore" } } )请注意,添加textScore是因为默认情况下文档没有根据分数进行排序。
https://stackoverflow.com/questions/35451058
复制相似问题