Mongodb错误"failed to use text index to satisfy $text query"



我正在尝试使用全文搜索。以这种方式设置索引

myRootSchema.index({ "_type": 1, "$**": "text" }); 

其中_type是鉴别器键,myRootSchema 是 4 个继承模式的父模式。

我收到此错误

{
"name": "MongoError",
"message": "error processing query: ns=MYDB.caseNotesTree: TEXT : query=title, language=english, caseSensitive=0, diacriticSensitive=0, tag=NULLnSort: {}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=NULLnSort: {}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)
    });

错误消息显示"如果文本索引是复合的,是否为所有前缀字段提供相等谓词?这意味着,在查询中还需要提供类型。您的查询不会这样做,因为它只使用索引的$text部分,而不使用索引的type部分。

这是

MongoDB中"text"索引的限制。根据通配符文本索引的 mongoDB 文档,如果有任何前面的键,则查询谓词必须包含前面键的相等匹配条件。有关文档,请参阅此处。

修改后的代码位$or: [ { _type: 'childA' },{ _type: 'childB' },{ _type: 'childC' },{ _type: 'childD' }可以看作是_type: {$in: ['childA', 'childB', 'childC', 'ChildD']}的,它与指定的限制不匹配,即必须存在相等条件。

要克服这个问题,您可以尝试使用通配符文本字段创建复合索引,然后是其他键,如下所示。

myRootSchema.index({ "$**": "text" , "_type": 1}); 

这工作正常。但它没有优化。

如果您正在考虑优化查询,则必须在两个不同的查询中分别使用过滤器,直到 Mongo 放宽限制。

最新更新