【发布时间】:2017-07-17 01:19:20
【问题描述】:
假设我有一个 mongo 集合,在 itemName 字段上有一个 text index,其中包含这 3 个文档:
{
_id: ...,
itemName: 'Mashed carrots with big carrot pieces',
price: 1.29
},
{
_id: ...,
itemName: 'Carrot juice',
price: 0.79
},
{
_id: ...,
itemName: 'Apple juice',
price: 1.49
}
然后我执行如下查询:
db.items.find({ $text: { $search: 'Car' } }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );
如何强制 mongo 返回以“Car”开头的文档(不区分大小写)在返回任何其他在 itemName 某处也包含“Car”的文档之前字符串?
所以我想按以下顺序检索文档:
[
{..., itemName: 'Carrot Juice', ...},
{..., itemName: 'Mashed carrots with big carrot pieces', ...}
]
当然,这是在搜索功能中使用的,因此在显示之后的任何其他项目之前,向用户显示以他的搜索字符串开头的项目是完全有意义的。
直到现在我都在使用标准的正则表达式,但这里的性能当然要差得多! + 因为我必须搜索不区分大小写,根据文档,正常的正则表达式根本不使用任何索引?!
编辑:
另外,有时$text 的行为很奇怪。
例如,我有大约 10-15 个项目,其中itemName 以单词“Zwiebel”开头。
这个查询
db.items.find({ $text: { $search: "Zwiebel" }, supplier_id: 'iNTJHEf5YgBPicTrJ' }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );
像一个魅力一样工作并返回所有这些文档,而这个查询
db.items.find({ $text: { $search: "Zwie" }, supplier_id: 'iNTJHEf5YgBPicTrJ' }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );
不返回任何东西!只需将$search 中的“Zwiebel”更改为“Zwie”即可。
我真的不明白这怎么可能?!
最好的,P
【问题讨论】:
-
按textScore排序有什么作用?
-
请检查我的编辑! :-) 谢谢!
-
@PatrickDaVader 查看我的编辑
-
@PatrickDaVader 全文搜索不适用于子字符串匹配 - 如果“Zwei”和“Zweibel”是完全不同的词,那么搜索“Zwei”应该不匹配带有“Zweibel”的记录,即您所看到的是正确的行为。
标签: mongodb indexing fulltext-index