草庐IT

scala - Casbah & Rogue for MongoDB - 查询功能

coder 2023-10-28 原文

我目前正在使用 Casbah 和 MongoDB 来实现网络服务。到目前为止,我没有遇到任何问题。我也在使用 Scala。

但是,我只是想知道是否有比 Casbah 更好的东西来执行大量 find/findOne 类型的查询。

我遇到了 Rogue,这是一种基于 Scala 的类型安全 DSL,据说可以使查询更容易、更具可读性。

所以,我想知道转向 Rogue 是否有用,以便随着 Web 服务项目变得越来越大和越来越复杂,让 Rogue 支持查询可能会有所帮助?

只是想知道我是否应该继续或转向更好的东西。

最佳答案

目前,Rogue 仅适用于 Lift's MongoDB-Record系统。

它提供完全类型安全的部分原因是它为 Lift-Record 使用了一个强大的、定义良好的对象结构。由于您拥有完整的结构,因此您进行“自由形式”查询的能力要差得多。这就是我在最近的 Scala 网络研讨会上所做的 Lift-Record + Rogue 演示的意思。自从我这样做以来,Lift & Rogue 中的一些内容发生了变化,因此代码可能略微过时但仍然具有代表性。这是 MongoDB 的提升记录模型:

object LiftRecordDemo extends Application {
  // We'll use enums for Type and Subtype
  object EventType extends Enumeration {
    type EventType = Value
    val Conference, Webinar = Value
  }

  object EventSubType extends Enumeration {
    type EventSubType = Value
    val FullDay = Value("Full Day")
    val HalfDay = Value("Half Day")
  }



  class MongoEvent extends MongoRecord[MongoEvent] with MongoId[MongoEvent] {
    def meta = MongoEvent

    object name extends StringField(this, 255)
    object eventType extends EnumField(this, EventType) 
    object eventSubType extends OptionalEnumField(this, EventSubType)
    object location extends JsonObjectField[MongoEvent, EventLocation](this, EventLocation)  {
      def defaultValue = EventLocation(None, None, None, None, None, None, None)
    }

    object hashtag extends OptionalStringField(this, 32)
    object language extends OptionalStringField(this, 32)
    object date extends JsonObjectField[MongoEvent, EventDate](this, EventDate) {
      def defaultValue = EventDate(new DateTime, None)
    }

    object url extends OptionalStringField(this, 255)
    object presenter extends OptionalStringField(this, 255)

  }

  object MongoEvent extends MongoEvent with MongoMetaRecord[MongoEvent] {
    override def collectionName = "mongoEvents"
    override def formats = super.formats + new EnumSerializer(EventType) + new EnumSerializer(EventSubType)
  }


  case class EventLocation(val venueName: Option[String], val url: Option[String], val address: Option[String], val city: Option[String], val state: Option[String], val zip: Option[String], val country: Option[String]) extends JsonObject[EventLocation] {
    def meta = EventLocation
  }

  object EventLocation extends JsonObjectMeta[EventLocation]

  case class EventDate(start: DateTime, end: Option[DateTime]) extends JsonObject[EventDate] {
    def meta = EventDate
  }

  object EventDate extends JsonObjectMeta[EventDate]
}

如您所见,您需要提前定义您的 MongoDB 数据模型,以便获得强类型、安全查询的好处……Rogue 在编译时强制执行其中的大部分。以下是针对此模型的一些 Rogue 示例:

  // Tell Lift about our DB
  val mongoAddr = MongoAddress(MongoHost("127.0.0.1", 27017), "scalaWebinar")

  MongoDB.defineDb(DefaultMongoIdentifier, mongoAddr)

  // Rogue gives us a saner approach, although still hobbled by some
  // of Lift-MongoDB-Record's limits on embedded docs

  val q = MongoEvent where (_.eventType eqs EventType.Webinar)

  println("Rogue created a Query '%s'\n\n".format(q))

  for (x <- MongoEvent where (_.eventType eqs EventType.Webinar)) {
    println("Name: %s Presenter: %s\n".format(x.name, x.presenter))
  }

  // Rogue can also do sorting for you, which is useful

  println("\n\n\n")

  for (x <- MongoEvent where (_.eventType eqs EventType.Conference) 
                       orderAsc(_.language) andDesc(_.name)) { 
    println("Name: %s Language: %s\n".format(x.name, x.language))
  }
  val start = new DateTime(2011, 2, 1, 0, 0, 0, 0)
  val end = new DateTime(2011, 3, 1, 0, 0, 0, 0)

    /** The following would be nice but unfortunately, 
      doesn't work because of lift's current embedded doc
      implementation
    */
  //val dateQ = MongoEvent where (_.date.start after start) 
                           //and (_.date.end before end)

请注意,我并不是说 Rogue 和 Lift-Record 不好,只是说它们基于一个强定义的编译时数据模型。

相反,如果您想使用与 Casbah 类似的上下文,我们确实有一个内置 DSL,它旨在尽可能接近地模仿 MongoDB 的内置查询模型。它适用于任何任意底层模型,但在可能的情况下会执行很多类型安全级别。这是 Casbah 查询的一个示例(由于来自同一演示文稿而略有过时):

  // What about querying?  Lets find all the non-US events

  for (x <- mongo.find(MongoDBObject("location.country" -> 
                        MongoDBObject("$ne" -> "USA")))) println(x)

  /* There's a problem here: We got back the Webinars too because 
     They don't have a country at all, so they aren't "USA"
    */
  println("\n\nTesting for existence of Location.Country:")

  for (x <- mongo.find(MongoDBObject("location.country" -> MongoDBObject(
                       "$ne" -> "USA",
                       "$exists" -> true 
                      )))) println(x)

  // This is getting a bit unwieldy.  Thankfully, Casbah offers a DSL
  val q = $or ("location.country" -> "USA", "location.country" -> "Japan")

  println("\n Created a DBObject: %s".format(q))

  println("\n Querying using DSL Object...")

  for (x <- mongo.find(q)) println(x)

  // It's possible to construct more complex queries too.

  // Lets find everything in February

  println("\n February Events...")
  val start = new DateTime(2011, 2, 1, 0, 0, 0, 0)
  val end = new DateTime(2011, 3, 1, 0, 0, 0, 0)
  val dateQ = "date.start" $gte start $lt end 

  println("\n Date Query: %s".format(dateQ))

  for (x <- mongo.find(dateQ, MongoDBObject("name" -> true, "date" -> true))) println(x)

值得注意的是,我们正在查询自由形式模型,但使用 DSL 运算符而不是嵌套的 MongoDB 定义。有很多很棒的运算符映射,一直到 $type 运算符,使用类 list 测试类型以确保编译时安全:

"Casbah's $type operator" should {
  "Accept raw Byte indicators (e.g. from org.bson.BSON)" in {
    // Don't need to test every value here since it's just a byte
    val typeOper = "foo" $type org.bson.BSON.NUMBER_LONG
    typeOper must notBeNull
    typeOper.toString must notBeNull
    typeOper must haveSuperClass[DBObject]
    typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.NUMBER_LONG))
  }

  "Accept manifested Type arguments" in {
    "Doubles" in {
      val typeOper = "foo".$type[Double]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.NUMBER))
    }
    "Strings" in {
      val typeOper = "foo".$type[String]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.STRING))
    }
    "Object" in {
      "via BSONObject" in {
        val typeOper = "foo".$type[org.bson.BSONObject]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.OBJECT))
      }
      "via DBObject" in {
        val typeOper = "foo".$type[DBObject]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.OBJECT))
      }
    }
    "Array" in {
      "via BasicDBList" in {
        val typeOper = "foo".$type[BasicDBList]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.ARRAY))
      }
      "via BasicBSONList" in {
        val typeOper = "foo".$type[org.bson.types.BasicBSONList]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.ARRAY))
      }
    }
    "OID" in {
      val typeOper = "foo".$type[ObjectId]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.OID))
    }
    "Boolean" in {
      val typeOper = "foo".$type[Boolean]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.BOOLEAN))
    }
    "Date" in {
      "via JDKDate" in {
        val typeOper = "foo".$type[java.util.Date]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.DATE))
      }
      "via Joda DateTime" in {
        val typeOper = "foo".$type[org.joda.time.DateTime]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.DATE))
      }
    }
    "None (null)" in {
      // For some reason you can't use NONE 
      val typeOper = "foo".$type[Option[Nothing]]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.NULL))
    }
    "Regex" in {
      "Scala Regex" in {
        val typeOper = "foo".$type[scala.util.matching.Regex]
        typeOper must notBeNull
        typeOper.toString must notBeNull
        typeOper must haveSuperClass[DBObject]
        typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.REGEX))
      }
    }
    "Symbol" in {
      val typeOper = "foo".$type[Symbol]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.SYMBOL))
    }
    "Number (integer)" in {
      val typeOper = "foo".$type[Int]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.NUMBER_INT))
    }
    "Number (Long)" in {
      val typeOper = "foo".$type[Long]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.NUMBER_LONG))
    }
    "Timestamp" in {
      val typeOper = "foo".$type[java.sql.Timestamp]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.TIMESTAMP))
    }
    "Binary" in {
      val typeOper = "foo".$type[Array[Byte]]
      typeOper must notBeNull
      typeOper.toString must notBeNull
      typeOper must haveSuperClass[DBObject]
      typeOper must beEqualTo(nonDSL("foo", "$type", org.bson.BSON.BINARY))
    }

  }

(注意:您需要将 casbah-query 包及其相关导入导入到您的代码中,或者使用来自预模块化的默认“casbah”导入)。 Casbah 的规范目前已完全涵盖每个 DSL 运营商;目前文档滞后,但 Specs 很好地介绍了它们的用法。请注意,Casbah 中有两种 运算符,就像在 MongoDB 中一样。

Bareword Operators, in which the leftmost part of the statement is the $ Operator. Examples of this are $set, $rename, etc. See the Specs for Bareword Operators for more.

"Core" Operators, are operators that exist on the right hand side of the statement, such as $type. See the Specs for Core Operators for more.

我知道这是一个相当详细的答案,但我想确保您了解您的选择,以及这两种解决方案的局限性。 Casbah 将为您提供一个与 MongoDB 紧密映射的 DSL,并删除一些语法上的麻烦(请记住,Casbah 在 DBObject 上提供了一个 getAs[T] 方法来请求DBObject 中的值作为特定 类型,人们经常忽略);许多用户在寻求一些东西来做内置的事情之前并不知道 DSL 的存在。但是,在某些人看来,Casbah 的查询 DSL 也看起来有点“笨拙”......作为它的作者我更喜欢它的简单和优雅,因为我只需要记住用于查询的 **MONGODB* 语法,而不是 MongoDB 和另一个 DSL。它还基于自由形式查询,并且不提供与 Rogue 相同的结构化、编译时类型安全和感知功能。

相比之下,Rogue 还需要针对它的完全定义的 Record 模型,这并不适合每个应用程序。

不过,如果您的需求有一个“中间地带”,而这两种产品都不能很好地满足,我很想知道这两种产品的哪些方面可以改进。

关于scala - Casbah & Rogue for MongoDB - 查询功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5951875/

有关scala - Casbah & Rogue for MongoDB - 查询功能的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  5. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  6. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  9. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐