繁体   English   中英

如何使用Casbah和Subset管理多个级别的对象?

[英]How to manage multiple levels of Objects using Casbah and Subset?

我有三个对象

case class Metric(val name: String, val tags: Map[String, String]) 

case class Threshold(val metric: Metric, val critical: Long, val warning: Long)

class Profile(val name: String, val thresholds: List[Threshold])

我打算将Profile对象仅存储在Mongo DB中,但是在Scala App中,它们应该由其类型表示。

我正在使用Subset并具有以下性质

implicit val reader = ValueReader[Threshold]({
case metric(metric) ~ critical(critical) ~ warning(warning) =>
  new Threshold(metric, critical, warning)
})
implicit val writer = {
def f(threshold: Threshold): DBObject =
  (metric -> threshold.metric) ~ (critical -> threshold.critical) ~ (warning -> threshold.warning)
ValueWriter(f _)
} 

如何查询Mongo Now? 有什么例子吗?

集成测试是一个很好的例子,说明如何使用嵌套对象,查询,更新等。该测试的各个部分也分散在整个文档中。

如果您打算从Mongo中读取内容,则需要模型所有部分的读者。 如果您打算查询或更新,则还需要编写者。 如果Scala编译器找不到必需的隐式编译器,则应发出错误。

您将如何查询Profile

object Profile {
  val name = "name".fieldOf[String]
  val thresholds = "thresholds".subset(Threshold).of[List[Threshold]]

  // typical query:
  def alarmsFor(metric: String) =
    collection.find( thresholds elemMatch {t =>
      t.metric.where{_.name == metric} && t.critical > 10
    } ) map {
      case name(n) ~ thresholds(t) => new Profile(n, t)
    }
}

在此代码段中,我做了几个假设:

  • Threshold的字段在object Threshold中定义( t是获得object Threshold位置)
  • Threshold.metric字段本身就是一个子集 ,例如val metric = "metric".subset(Metric).of[Metric] ,因此您可以查询metric.where{_.name == metric}

请注意,从0.7.0版开始,仍然没有Map[String,T]读取器/写入器(尽管我计划最终使用)–您将不得不开发它(如果需要此字段)或解决该问题Metric的读取器/写入器中的此问题。

暂无
暂无

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

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