RethinkDb基于现有值更新表行

问题描述 投票:0回答:1

我在RethinkDb中有一个简单的表,我需要更新现有的行,这是一个非常简单的表,只有两列Idvalue每当我有一个相同的Id的新记录我想为现有值添加新值,例如如果我在表中有一行值{id: 25 , value:50}并且我有一个新记录{id:25 , value:100}该行应该更新为{id : 25, value 150}

在Java文档中,我发现这个例子似乎符合我的要求https://www.rethinkdb.com/api/java/update/

r.table("posts").get(1).update(
    post -> r.hashMap("views", post.g("views").add(1).default_(0))
).run(conn);

但是,我无法在我的代码中运行此示例,因为我收到此错误Missing parameter type: post

enter image description here

我正在使用scala和RethinkDb java驱动程序连接到rethinkDb

scala rethinkdb
1个回答
0
投票

我正在评估rethinkdb,试过这段代码:

package de.jvr

import com.rethinkdb.RethinkDB

object Test {

 def main(args: Array[String]): Unit = {


  // database
  val r = RethinkDB.r
  val conn = r.connection().hostname("localhost").port(28015).connect()

  try {
   // existing database "test"

   // drop table
   r.db("test").tableDrop("posts").run(conn)

   // create table
   r.db("test").tableCreate("posts").run(conn)

   // insert
   r.table("posts").insert(
    r.hashMap("id", 25)
    .`with`("value", "50")
   ).run(conn);

   // update
   r.table("posts").get(25).update(r.hashMap("value", "100")).run(conn);

   //print
   val cursorJava: com.rethinkdb.net.Cursor[java.util.HashMap[String, String]] = r.table("posts").run(conn)
   cursorJava forEach(x => println(x))

   // or in the Data Explorer: r.table("posts")
  } catch {
   case e:Throwable => println("exception: " + e.toString)
  }


 sys.exit(0)
 }
}

/*

Cmd-line结果:[info] {id = 25,value = 100}

Data Explorer:

返回1行。显示行1-1 {

“id”:25,“value”:“100”

}

在build.sbt中有这个选项:

fork in run:= true

trapExit:= false

scalacOptions ++ = Seq(“ - Xexperimental”)* /

© www.soinside.com 2019 - 2024. All rights reserved.