繁体   English   中英

Scala Casbah DSL查询

[英]Scala casbah DSL queries

我正在学习Scala并尝试Mongo。 我正在创建一个函数,该函数接收Map[String, Any]作为参数,并且我想为其返回正确的MongoDBObject

def parse(query: Map[String, Any]): MongoDBObject = {
  val result = query("operation") match {
    case "all" => query("field").toString $all query("value").asInstanceOf[List[String]]
    case "in" => query("field").toString $in query("value").asInstanceOf[List[String]]
    case "regex" => query("field").toString $regex query("value")
    case "eq" => query("field").toString $eq query("value")
    case "gt" => query("field").toString $gt query("value")
    case "gte" => query("field").toString $gte query("value")
    case "lt" => query("field").toString $lt query("value")
    case "lte" => query("field").toString $lte query("value")
    case "exists" => query("field").toString $exists query("value").asInstanceOf[Boolean]
    case "size" => query("field").toString $size query("value").asInstanceOf[Int]
    case "where" => $where(query("value").toString)
    case _ => throw new NotImplementedError("Unknown operation")
  }
}

我有一些问题。

  • 编译器说$regex不是String的成员。 我不知道为什么
  • 编译器说Any不是有效的查询参数。 我想应该将其转换为int,字符串,日期或任何其他有效的Mongo类型。 有没有办法解决这个问题而无需反思来解决该值是什么类型?
  • 对于$mod操作,我应该给两个数值作为参数。 我应该使用List作为地图的值并获取第一项和第二项吗?

它抱怨$regex因为它没有在右侧找到可用于正则表达式的对象来应用用于解析$regex方法的转换-这也是您在以下所有调用中都会遇到的问题。

对于Any (以及$mod )的问题,我是否可以建议其他方法? 您没有使用Any类型信息,因此您无法真正避免运行时强制转换(而且我也不知道反射对您有何帮助。)您不会以这种方式获得静态类型系统的任何好处。 这是您可以使用类型层次结构强制执行类型安全性的方法的示意图:

sealed trait Query

case class All(field: String, value: List[String]) extends Query 
...
case class GreaterThan(field: String, value: Int) extends Query 
...
case class Mod(field: String, divisor: Int, remainder: Int) extends Query

def parse(q: Query): MongoDBObject = {
   q match {
      case All(f, v) => f $all v
      ...
      case GreaterThan(f, v) => f $gt v
      ...
      case Mod(f, d, r) => f $mod (d, r)
   }
}

或者,您可以在Query上定义一个抽象的execute方法,并在每个扩展类中覆盖它,而不是在parse中执行match语句。 从那里,您可以进一步使用类型参数或泛型类型进行抽象,以允许例如GreaterThan接受任何Numeric类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM