我正在尝试提供一个 API 来根据各种条件搜索 MongoDB 集合,包括全文搜索。由于这是一个 Scala 项目(在 Play FWIW 中),我正在使用Salat ,它是围绕Casbah的抽象。
以下代码工作正常:
MySalatDao
.find(MongoDBObject("$text" -> MongoDBObject("$search" -> "Vidya")), MongoDBObject("score" -> MongoDBObject("$meta" -> "textScore")))
.sort(orderBy = MongoDBObject("score" -> MongoDBObject("$meta" -> "textScore")))
但是,我最终需要搜索多个条件并按全文搜索分数对结果进行排序,因此我探索了 Casbah 的 MongoDBObject查询构建器功能(在底部)。
所以我试图像这样复制上面的内容:
val builder = MongoDBObject.newBuilder
builder += "$text" -> MongoDBObject("$search" -> "Vidya")
builder += "score" -> MongoDBObject("$meta" -> "textScore")
MySalatDao
.find(a.result())
.sort(orderBy = MongoDBObject("score" -> MongoDBObject("$meta" -> "textScore")))
这给出了以下异常:
com.mongodb.MongoException: Can't canonicalize query: BadValue must have $meta projection for all $meta sort keys
at com.mongodb.QueryResultIterator.throwOnQueryFailure(QueryResultIterator.java:214)
at com.mongodb.QueryResultIterator.init(QueryResultIterator.java:198)
at com.mongodb.QueryResultIterator.initFromQueryResponse(QueryResultIterator.java:176)
at com.mongodb.QueryResultIterator.<init>(QueryResultIterator.java:64)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:86)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
.
.
我以前见过这个错误——当我没有score
在查询中包含组件时。但是一旦我这样做了,它就起作用了(如第一个代码片段所示),我认为带有查询构建器的版本是等效的。
就此而言,调用builder.result().toString()
产生这个:
{ "$text" : { "$search" : "Vidya"} , "score" : { "$meta" : "textScore"}}
让查询生成器为我工作的任何帮助将不胜感激。