2012-02-01 16 views
0

我有三個對象如何使用Casbah和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]) 

我打算只存儲配置文件對象蒙戈DB,但在斯卡拉應用程序,他們應該通過它們的類型來表示。

我使用的子集爲同和定義下列性質

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 _) 
} 

我如何可以查詢到從蒙戈現在? 這個附近的任何例子?

回答

1

Integration test是如何使用嵌套對象,查詢,更新等的一個很好的例子。這個測試的部分也分散在documentation之間。

如果您打算從Mongo中讀取數據,您需要讀者來獲取模型的所有部分。如果你打算查詢或更新,你也需要編寫者。如果Scala編譯器找不到必要的隱式,它應該發出一個錯誤。

你會如何查詢Profile S:

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就是你它)
  • Threshold.metric字段是子集本身,例如val metric = "metric".subset(Metric).of[Metric],這樣就可以查詢metric.where{_.name == metric}

注意,從0.7.0版本仍有Map[String,T]沒有讀/寫器(雖然我打算把它最終) - 你必須發展它(如果你需要這個字段),或者在Metric的讀寫器中解決這個問題。

+0

假設是公平的,使事情更清晰。謝謝 – sheki 2012-02-01 12:31:07