我目前在使用 MongoDB 中的全文搜索功能时遇到一些问题。特别是在尝试匹配确切的短语时。
我正在测试 mongo shell 中的功能,但最终我将使用 Spring Data MongoDB 和 Java。
因此,我首先尝试运行此命令来搜索单词“delay”、“late”和短语“on time”
db.mycollection.find( { $text: { $search: "delay late \"on time\"" } }).explain(true);
结果解释查询告诉我:
"parsedTextQuery" : {
"terms" : [
"delay",
"late",
"time"
],
"negatedTerms" : [ ],
"phrases" : [
"on time"
],
"negatedPhrases" : [ ] },
这里的问题是我不想搜索“time”这个词,而是搜索“on time”这个短语。我确实想搜索延迟和迟到的情况,并且理想情况下不想阻止词干。
我尝试了一些不同的排列,例如
db.mycollection.find( { $text: { $search: "delay late \"'on time'\"" } }).explain(true);
db.mycollection.find( { $text: { $search: "delay late \"on\" \"time\"" } }).explain(true);
但似乎无法得到正确的结果。我在文档中看不到任何关于此的明显内容。
出于我的目的,我应该使用单个单词的全文搜索和短语的正则表达式搜索功能吗?
当前使用 MongoDB 版本 2.6.5。谢谢。
最佳答案
您是否尝试过文本搜索以查看其行为是否不正确?它在 MongoDB 2.6.7 上按我的预期工作:
> db.test.drop()
> db.test.insert({ "t" : "I'm on time, not late or delayed" })
> db.test.insert({ "t" : "I'm either late or delayed" })
> db.test.insert({ "t" : "Time flies like a banana" })
> db.test.ensureIndex({ "t" : "text" })
> db.test.find({ "$text" : { "$search" : "time late delay" } }, { "_id" : 0 })
{ "t" : "I'm on time, not late or delayed" }
{ "t" : "Time flies like a banana" }
{ "t" : "I'm either late or delayed" }
> db.test.find({ "$text" : { "$search" : "late delay" } }, { "_id" : 0 })
{ "t" : "I'm on time, not late or delayed" }
{ "t" : "I'm either late or delayed" }
> db.test.find({ "$text" : { "$search" : "late delay \"on time\"" } }, { "_id" : 0 })
{ "t" : "I'm on time, not late or delayed" }
为什么解释中的terms
数组中是“time”?因为如果文档中出现短语“on time”,则术语“time”也必须出现。 MongoDB 会尽可能使用文本索引来帮助定位短语,然后检查索引结果以查看哪个实际与完整短语匹配,而不仅仅是短语中的术语。
关于MongoDB 全文搜索 - 匹配单词和精确短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28368883/