CQL 包含一个BEGIN BATCH...APPLY BATCH 语句,允许您对多个插入进行分组,以便开发人员可以创建和执行一系列请求
(见http://www.datastax.com/dev/blog/client-side-improvements-in-cassandra-2-0)。
以下对我有用(Scala):
PreparedStatement ps = session.prepare(
"BEGIN BATCH" +
"INSERT INTO messages (user_id, msg_id, title, body) VALUES (?, ?, ?, ?);" +
"INSERT INTO messages (user_id, msg_id, title, body) VALUES (?, ?, ?, ?);" +
"INSERT INTO messages (user_id, msg_id, title, body) VALUES (?, ?, ?, ?);" +
"APPLY BATCH" );
session.execute(ps.bind(uid, mid1, title1, body1, uid, mid2, title2, body2, uid, mid3, title3, body3));
如果事先不知道要执行哪些语句,可以使用以下语法(Scala):
var statement: PreparedStatement = session.prepare("INSERT INTO people (name,age) VALUES (?,?)")
var boundStatement = new BoundStatement(statement)
val batchStmt = new BatchStatement()
batchStmt.add(boundStatement.bind("User A", "10"))
batchStmt.add(boundStatement.bind("User B", "12"))
session.execute(batchStmt)
注意: BatchStatement 最多只能容纳 65536 条语句。我很难学到这一点。 :-)