【发布时间】:2020-05-10 18:45:43
【问题描述】:
我正在尝试使用全文搜索。这样设置索引
myRootSchema.index({ "_type": 1, "$**": "text" });
其中 _type 是一个 discriminatorKey,myRootSchema 是 4 个继承模式的父模式。
我收到此错误
{
"name": "MongoError",
"message": "error processing query: ns=MYDB.caseNotesTree: TEXT : query=title, language=english, caseSensitive=0, diacriticSensitive=0, tag=NULL\nSort: {}\nProj: {}\n planner returned error: failed to use text index to satisfy $text query (if text index is compound, are equality predicates given for all prefix fields?)",
"waitedMS": 0,
"ok": 0,
"errmsg": "error processing query: ns=MYDB.caseNotesTree: TEXT : query=title, language=english, caseSensitive=0, diacriticSensitive=0, tag=NULL\nSort: {}\nProj: {}\n planner returned error: failed to use text index to satisfy $text query (if text index is compound, are equality predicates given for all prefix fields?)",
"code": 2
}
尝试这个查询
Model
.find(
{ $text : { $search :req.query.q } }
)
.exec(function(err, data) {
if(err)res.json(err)
res.json(data)
});
编辑: 按照建议,我应该在查询中设置 _type 字段,但 _type 是“自动填充的”,因为它是一个鉴别器。具有单个 _type 的查询有效,但我不需要,我必须查询 4 个继承模型。 我什至尝试了 $or,但没有出现同样的错误。
Model
.find(
{ $or: [ { _type: 'childA' },
{ _type: 'childB' },
{ _type: 'childC' },
{ _type: 'childD' }
], $text : { $search :req.query.q } }
)
.exec(function(err, data) {
if(err)console.log(err)
res.json(data)
});
【问题讨论】:
-
Combine full text with other index 的可能副本,它实际上回答了问题,而不仅仅是引用文档。
-
Model是您的根模型还是您的 4 个继承模式之一的模型? -
对,
_type只会添加到您对继承模型的查询中。而不是$or,您是否尝试添加_type: {$in: ['childA', 'childB', 'childC', 'childD']}? -
不行,我刚试过,不行。
-
那么我认为您不能在使用
$text查询的同时查询多个_type值,考虑到复合索引的构造方式,这很有意义。您需要分别$text查询每个_type,然后将结果合并在一起;有效地创建您自己的$or查询。