我正在尝试使用 datastax java 驱动程序来更新和查询具有映射字段的列族。有没有人举例说明如何将 cql 集合与 Datastax Java 驱动程序一起使用?
谢谢
我正在尝试使用 datastax java 驱动程序来更新和查询具有映射字段的列族。有没有人举例说明如何将 cql 集合与 Datastax Java 驱动程序一起使用?
谢谢
通常我会问您尝试了什么,但我知道这不在 Java 驱动程序的 DataStax 文档中。我会经历对我有用的东西。
有几点需要注意:
cqlsh
如果您想查看它们在应用程序之外的内容,则需要通过命令行检查它们的值。要更新现有行(在具有 的“用户”表中Map<varchar,varchar> phone_numbers
),请尝试以下操作:
String cqlQuery = "UPDATE users SET phone_numbers = phone_numbers + ";
cqlQuery += "{'" + phoneType + "':'" + phoneNumber+ "'} ";
cqlQuery += "WHERE username = ?";
PreparedStatement preparedStatement = getSession().prepare(cqlQuery);
BoundStatement boundStatement = preparedStatement.bind(user);
getSession().execute(boundStatement);
更好的方法(假设 a Map<String,String> phoneNumbers
)是将集合绑定到准备好的语句,如下所示:
String cqlQuery = "UPDATE users SET phone_numbers = ? ";
cqlQuery += "WHERE username = ?";
PreparedStatement preparedStatement = getSession().prepare(cqlQuery);
BoundStatement boundStatement = preparedStatement.bind(phoneNumbers,user);
getSession().execute(boundStatement);
同样,将其读回:
String cqlQuery2 = "SELECT phone_numbers FROM users WHERE username = ?";
PreparedStatement preparedStatement2 = getSession().prepare(cqlQuery2);
BoundStatement boundStatement2 = preparedStatement2.bind(user);
ResultSet result2 = getSession().execute(boundStatement2);
Map<String,String> newMap = result2.one().getMap("phone_numbers", String.class, String.class);
他们今天刚刚在DataStax Academy的(免费)CAS101J 课程中介绍了这一点。
我将在当前的 Java 驱动程序文档中添加一些使用 CQL 集合以及简单语句和准备语句的示例。
您可以将 CQL 集合与准备好的语句一起使用。快速入门部分的 Java 驱动程序文档中有一个示例。
第 4 步将 Java HashSet 对象绑定到歌曲表中的 CQL 集列。
这是我的做法;这具有 Cassandra 中元组列的映射以及 Cassandra 中的映射列。我将 Scala 与 DataStax Cassandra Java 驱动程序一起使用
需要进口
import java.lang
import java.text.SimpleDateFormat
import com.datastax.driver.core._
import com.datastax.driver.core.querybuilder.QueryBuilder
import scala.collection.Map
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import com.datastax.spark.connector.cql.CassandraConnector
import org.apache.spark.rdd.RDD
import scala.collection.JavaConversions._
代码片段
val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy H:mm:ss")
val start_date: java.util.Date = simpleDateFormat.parse(val("StartTime").replaceAll(":(\\s+)", ":"))
val b_tuple= session.getCluster().getMetadata().newTupleType(DataType.cint(), DataType.cint(), DataType.text())
val time_tuple = session.getCluster().getMetadata().newTupleType(DataType.timestamp(), DataType.timestamp())
val time_tuple_value = time_tuple.newValue(start_date, end_date)
val b_tuple_value = bin_cell_tuple.newValue(b._1: lang.Integer, b._2: lang.Integer, val("xxx"))
val statement_2: Statement = QueryBuilder.insertInto("keyspace", "table_name")
.value("b_key", bin_cell_tuple_value)
.value("time_key", time_tuple_value)
.value("some_map", mapAsJavaMap(my_scala_map))
session.executeAsync(statement_2)