notes
notes copied to clipboard
MongoDB $text $search wildcard 模糊匹配
背景
话说,企图用 MongoDB 全文检索来替代搜索引擎的可以放弃了。 什么分词、评分就不说了,连模糊匹配都做不到。
建议
实在需要的,可以配合上正则检索一起使用。
// demo for find
db.articles.find(
{ $or: [
{ $text: { $search: "cake" } },
{ my_field_a: /cake/ }, // my_field_a 必须建立索引
{ my_field_b: /cake/ }, // my_field_b 必须建立索引
...
] }
);
// demo for aggregate
db.articles.aggregate(
[ { $match: {
$or: [
{ $text: { $search: "cake" } },
{ my_field_a: /cake/ }, // my_field_a 必须建立索引
{ my_field_b: /cake/ }, // my_field_b 必须建立索引
...
]
} ]
);
但是注意两个事情:
1. 需要始终将 $text 放在第一部分的位置。 2. 必须为需要正则匹配的字段建立索引。
不然,你可能会得到类似以下的错误:
planner returned error: Failed to produce a solution for TEXT under OR - other non-TEXT clauses under OR have to be indexed as well
吐槽
MongoDB text search 还只是个孩子...

参考文档:
- https://docs.mongodb.com/manual/text-search/
- https://docs.mongodb.com/manual/reference/operator/query/text
- https://docs.mongodb.com/manual/tutorial/text-search-in-aggregation/