[英]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.