$ text搜索可以执行部分​​匹配

时间:2017-09-18 21:07:18

标签: mongodb mongodb-query

好的,所以我对此行为感到非常困惑。它似乎不一致和奇怪,特别是因为我读过Mongo不应该支持全文搜索中的部分搜索术语。我使用的是Mongo DB社区服务器版本3.4.7。我正在从Mongo shell进行这些测试。

所以,我有一个分配了文本索引的Mongo DB集合。我创建了这样的索引:

db.submissions.createIndex({"$**":"text"})

此集合中有一个文档包含以下两个值:

“雷格”

“鲍勃博士”。

我的目标是对包含多个匹配字词的文档进行文本搜索。

所以,这里是我运行的测试,以及它们不一致的输出:

单期,完成

db.submissions.find({"$text":{"$search":"\"Craig\""}})

结果:获取包含此值的文档。

单期,部分

db.submissions.find({"$text":{"$search":"\"Crai\""}})

结果:不返回任何内容,因为此部分搜索词与文档中的任何内容都不完全匹配。

多个条款,完整

db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bob\""}})

结果:返回包含这两个术语的文档。

多个条款,一个部分

db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bo\""}})

结果:尽管一个术语是部分术语,但返回包含两个术语的文档。文件中没有任何内容与“博士博士”匹配

多个条款,两个部分

db.submissions.find({"$text":{"$search":"\"Crai\" \"Dr. Bo\""}})

结果:返回包含两个术语的文档,尽管这两个术语都是部分和不完整的。文档中没有任何内容与“Crai”或“Bo博士”匹配。

问题

所以,这一切归结为:为什么?为什么会这样,当我使用只有一个值的部分术语进行文本搜索时,不会返回任何内容。当我用两个部分术语进行文本搜索时,我得到匹配结果?它看起来很奇怪而且不一致。

感谢。

2 个答案:

答案 0 :(得分:8)

MongoDB $text搜索不支持部分匹配。 MongoDB允许对字符串内容进行文本搜索查询,支持不区分大小写,分隔符,停用词和词干。默认情况下,搜索字符串中的术语是“或”。

逐一采用你的(非常有用的)例子:

单期,部分

// returns nothing because there is no world word with the value `Crai` in your
// text index and there is no whole word for which `Crai` is a recognised stem
db.submissions.find({"$text":{"$search":"\"Crai\""}})

多个条款,完整

// returns the document because it contains all of these words
// note in the text index Dr. Bob is not a single entry since "." is a delimiter
db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bob\""}})

多个条款,一个部分

// returns the document because it contains the whole word "Craig" and it 
// contains the whole word "Dr" 
db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bo\""}})

多个条款,两个部分

// returns the document because it contains the whole word "Dr"
db.submissions.find({"$text":{"$search":"\"Crai\" \"Dr. Bo\""}})

请记住$search字符串是......

  

MongoDB解析并用于查询文本索引的一串术语。除非指定为短语,否则MongoDB会对这些术语执行逻辑 OR 搜索。

因此,如果$search字符串中至少有一个术语匹配,则MongoDB与该文档匹配。

要验证此行为,如果您修改的文档会将Dr. Bob更改为DrBob,则以下查询将返回文档:

db.submissions.find({"$text":{"$search":"\"Craig\" \"Dr. Bo\""}})
db.submissions.find({"$text":{"$search":"\"Crai\" \"Dr. Bo\""}})

这些现在不会返回匹配项,因为Dr不再是文本索引中的整个单词,因为.分隔符后面没有它。

答案 1 :(得分:0)

您可以使用称为mongoose-fuzzy-search的mongoose外部库在mongoose数据库中进行部分搜索,在该库中,搜索文本以各种字谜分隔。 有关更多信息,请访问此link

User.fuzzySearch('jo').sort({ age: -1 }).exec(function (err, users) {
      console.error(err);
      console.log(users);
});