Casbah(Scala)使用嵌套条件生成查询语句($ OR $ AND)

时间:2015-05-11 16:03:04

标签: mongodb scala conditional-statements querydsl casbah

给定项目:$text = trim($text); 和模式:[{ prop1 : "a", prop2 : "b" , prop3, "c",....},....]

我想创建一个查询来查找与给定项匹配的所有模式。

生成的查询格式为:

[{ prop1 : "a", prop2 : "Any"},...]

我试图构建一个DSL表单,但是我在init上遇到了一个模糊的隐式错误:

可以使用这种表示法吗?或者我如何使用DBObject.Builder或MongoDbObjects实现它?

谢谢, 利

((A or B or C) AND (D or E or F) AND (G or H or J))
or
((A or B or C) AND (D or E or F) AND (G or H or J))
or
((A or B or C) AND (D or E or F) AND (G or H or J))
....

1 个答案:

答案 0 :(得分:0)

dsl的$or$and部分需要一个可遍历的,没有一个就无法启动 - 因此编译错误。

如果你可以延迟创建查询的$and$or部分,直到你构建了遍历它可以工作:

import com.mongodb.casbah.query.Imports._

/* test data */
val thing1 = Map[String,String]("thing_type" -> "PC", "os"-> "Windows", "vendor"-> "lenova")
val thing2 = Map[String,String]("thing_type" -> "Tablet", "os"-> "iOS", "vendor"-> "Apple")
val things_list = List(thing1, thing2)
/* end test data */

val atts_for_search = List("thing_type", "os", "vendor" )
val ors = scala.collection.mutable.ListBuffer[DBObject]()
things_list.foreach ( thing => {
    var ands = scala.collection.mutable.ListBuffer[DBObject]()
    atts_for_search.foreach ( att => {
          ands += $or(att $eq thing(att),att $exists false,att $eq "Any")

    }) // foreach attribute
    ands  += $and(ands)
})
val pattern_query = $or(ors)

返回以下输出:

{"$or": [{ "$and": [{ "$or": [ { "thing_type" : "PC"} , { "thing_type" : { "$exists" : false}} , { "thing_type" : "Any"}]} , 
                    { "$or": [ { "os" : "Windows"} , { "os" : { "$exists" : false}} , { "os" : "Any"}]} , 
                    { "$or": [ { "vendor" : "lenova"} , { "vendor" : { "$exists" : false}} , { "vendor" : "Any"}]}]} , 
         { "$and": [{ "$or": [ { "thing_type" : "Tablet"} , { "thing_type" : { "$exists" : false}} , { "thing_type" : "Any"}]} , 
                    { "$or": [ { "os" : "iOS"} , { "os" : { "$exists" : false}} , { "os" : "Any"}]} , 
                    { "$or": [ { "vendor" : "Apple"} , { "vendor" : { "$exists" : false}} , { "vendor" : "Any"}]}]}]}