簡體   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