简体   繁体   English

使用 Scala 更新 Cassandra DB 中的字符串列表列

[英]Update a String list column in Cassandra DB with Scala

I'm new on Cassandra and Scala, I'm working on a Kafka consumer (written in Scala) that has to update a field of a row on Cassandra from data it receives.我是 Cassandra 和 Scala 的新手,我正在研究一个 Kafka 消费者(用 Scala 编写),它必须根据收到的数据更新 Cassandra 上一行的字段。 And so far no problem.到目前为止没有问题。

In this row a field is a String list and when I do the update this field hasn't to change, so I have to assign the same String list to it self.在这一行中,一个字段是一个字符串列表,当我进行更新时,这个字段没有改变,所以我必须自己分配相同的字符串列表。

UPDATE keyspaceName.tableName
SET fieldToChange = newValue
WHERE id = idValue
AND fieldA = '${currentRow.getString("fieldA")}'
AND fieldB = ${currentRow.getInt("fieldB")}
...
AND fieldX =  ${currentRow.getList("fieldX", classOf[String]).toString}
...

But I receive even the exception:但我什至收到例外:

com.datastax.driver.core.exceptions.SyntaxError: line 19:49 no viable alternative at input ']' (... 482                   AND fieldX =  [[listStringItem1]]...)

I currently haven't found anything that could help me through the web我目前还没有找到任何可以帮助我浏览网络的东西

The problem is that Scala's string representation of the list doesn't match to the Cassandra's representation of the list , so it generates errors.问题是 Scala 的 list 字符串表示与Cassandra 的 list 表示不匹配,因此会产生错误。

Instead of constructing the CQL statement directly in your code, it's better to use PreparedStatement and bind variables to it:与其直接在代码中构建 CQL 语句,不如使用PreparedStatement并将变量绑定到它:

  1. first, it will speedup the execution as Cassandra won't parse every statement separately;首先,它会加快执行速度,因为 Cassandra 不会单独解析每条语句;
  2. it will be easier to bind variables as you won't need to care about corresponding string representation绑定变量会更容易,因为您不需要关心相应的字符串表示

But be very careful with Scala - Java driver expects Java's lists, sets, maps, and base types, like, ints, etc.. You may look to java-driver-scala-extras package , but you'll need to compile it yourself, as it's not available on Maven Central.但要非常小心 Scala - Java 驱动程序需要 Java 的列表、集合、映射和基本类型,如 int 等。您可能会查看java-driver-scala-extras 包,但您需要自己编译它,因为它在 Maven Central 上不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM