MongoDB Can't canonicalize query: BadValue Too many text expressions

坚强是说给别人听的谎言 提交于 2021-02-19 05:20:26

问题


I am attempting to build a query for MongoDB in Java and I am running into this error, "Can't canonicalize query: BadValue Too many text expressions" whenever I run the query.

The database is full of documents with a text property that is indexed for full text searching. I am trying to build a query to find any documents that match one or more of the queries in queryList and are within a certain time range. It works fine if there is only one query in the queryList, but fails otherwise.

Any ideas?

BasicDBList queryList = new BasicDBList();

for(String queryString : queryStrings)
{
    queryList.add(new BasicDBObject("$text", new BasicDBObject("$search", queryString)));
}

BasicDBObject queries = new BasicDBObject("$or", queryList);

DBObject query =  QueryBuilder.start()
    .and(endpointQuery,
         QueryBuilder.start().put("time").greaterThan(minTime).get(),
         QueryBuilder.start().put("time").lessThan(maxTime).get())
    .get();

DBCursor cursor = tweets.find(query);

回答1:


The error is pretty exact. What you are trying to do is create "multiple text queries" inside an $or condition. MongoDB cannot do that and it is in fact stated in the first line of Restrictions in the manual page for $text.

Moreover, you are not supposed to do that, but rather specify one text index on your collection to search on multiple fields if required:

db.collection.ensureIndex({ "comments": "text", "title": "text" })

And then you probably want to assign weights as shown here.

But it seems all you are really asking is to search for "multiple terms". So you don't use an $or for this, but just submit the list of terms separated by spaces:

db.collection.find({ "$text": { "$search": "something else" } })

Any words in the space delimited list are then searched for within the context of whatever fields are within the text index, and any document that contains "any" of those words will be returned. With the results ordered by "weight" of more matches of the words in that list.



来源:https://stackoverflow.com/questions/29020211/mongodb-cant-canonicalize-query-badvalue-too-many-text-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!