简体   繁体   English

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

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

I have three objects 我有三个对象

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])

I plan to store only the Profile object in Mongo DB, but in the Scala App they should be represented by their types. 我打算将Profile对象仅存储在Mongo DB中,但是在Scala App中,它们应该由其类型表示。

I am using Subset for the same and have defined of the following nature 我正在使用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 _)
} 

How can I query to and from Mongo Now? 如何查询Mongo Now? Any examples around this? 有什么例子吗?

Integration test is a good example on how to work with nested object, query, update etc. Parts of this test are scattered across the documentation as well. 集成测试是一个很好的例子,说明如何使用嵌套对象,查询,更新等。该测试的各个部分也分散在整个文档中。

If you plan to read from Mongo, you need readers for all the parts of your model. 如果您打算从Mongo中读取内容,则需要模型所有部分的读者。 If you plan to query or update, you need writers as well. 如果您打算查询或更新,则还需要编写者。 Scala compiler should issue an error if it cannot find a necessary implicit. 如果Scala编译器找不到必需的隐式编译器,则应发出错误。

How would you query Profile s: 您将如何查询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)
    }
}

I've made a couple of assumptions in this snippet: 在此代码段中,我做了几个假设:

  • Threshold 's fields are defined in object Threshold ( t is where you get it) Threshold的字段在object Threshold中定义( t是获得object Threshold位置)
  • Threshold.metric field is a subset itself, eg val metric = "metric".subset(Metric).of[Metric] , so that you can query metric.where{_.name == metric} Threshold.metric字段本身就是一个子集 ,例如val metric = "metric".subset(Metric).of[Metric] ,因此您可以查询metric.where{_.name == metric}

Note that as of version 0.7.0 there is still no reader/writer for Map[String,T] (though I plan to have it eventually) -- you'll have to develop it (if you need this field) or work around this problem in Metric 's reader/writer. 请注意,从0.7.0版开始,仍然没有Map[String,T]读取器/写入器(尽管我计划最终使用)–您将不得不开发它(如果需要此字段)或解决该问题Metric的读取器/写入器中的此问题。

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

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