【问题标题】:Batch insert with Astyanax CQL3 API?使用 Astyanax CQL3 API 批量插入?
【发布时间】:2013-02-26 17:52:12
【问题描述】:

我知道我们可以使用类似这样的方式将单个记录插入 Cassandra(以下示例取自 here):

final String INSERT_STATEMENT = "INSERT INTO employees (empID, deptID, first_name, last_name) VALUES (?, ?, ?, ?);";

result = keyspace
    .prepareQuery(CQL3_CF)
    .withCql(INSERT_STATEMENT)
    .asPreparedStatement()
    .withIntegerValue(222)
    .withIntegerValue(333)
    .withStringValue("Eric")
    .withStringValue("Cartman")
    .execute();

是否可以使用 Astyanax 的 cql3 API(如 JDBC 的 executeBatch)进行批量插入(用于多条记录)?

注意:使用 Astyanax 的 MutationBatch(基于 Thrift,而不是 CQL)对我来说似乎不是一个选择,因为我遇到了与 this one 相同的问题。

【问题讨论】:

  • 为什么不循环执行呢?
  • 你能给我举个例子吗?不知道如何构造那个 for 循环。顺便说一句,似乎 CQL 不允许在一个插入语句中插入多行(如在 SQL 中),否则这将是我的尝试之一。

标签: java cassandra astyanax


【解决方案1】:

使用 Astyanax 实现以下目标:

使用 cqlsh:

cqlsh:TEST_KS> INSERT INTO "MESSAGE_CF" (KEY, "DELETED_RECEIVER", "DELETED_SENDER", "SENDER") 
               VALUES ('user-1241324', 'Yes', 'No', 'user@mail.com');
cqlsh:TEST_KS> SELECT * FROM "MESSAGE_CF";                                                                   
 key          | DELETED_RECEIVER | DELETED_SENDER | RECEIVER | SENDER
--------------+------------------+----------------+----------+---------------
 user-1241324 |              Yes |             No |     null | user@mail.com

使用 Astyanax:

    Keyspace keyspace = Astyanax.getKeyspaceContext();
    ColumnFamily<String, String> mail = new ColumnFamily<String, String>(
        keyspace.getKeyspaceName(), // CF Name
        StringSerializer.get(),   // Key Serializer
        StringSerializer.get());  // Column Serializer

    // You could start looping here to alter what data is being inserted  
    // or make the method take in parameters and call it multiple times.         
    String  cqlStatement = 
            "INSERT INTO MESSAGE_CF (KEY, DELETED_RECEIVER, DELETED_SENDER, SENDER) "
            + "VALUES ('user-1281324', 'Yes', 'No', 'user@mail.com');";

    // execute the insertion
    OperationResult<CqlResult<String, String>> result = 
        keyspace.prepareQuery(mail).withCql(cqlStatement).execute();

   // stop looping

作为说明:我无法使用准备好的语句来实现这一点,Astyanax 在他们的wiki(在准备好的 CQL 下)表明支持准备好的语句,但我使用的是 astyanax-1.56.21 和 @987654326缺少@函数。

另外,为了使这个工作不要忘记将您的 AstyanaxContext 设置为使用 CQL3。

 new com.netflix.astyanax.impl.AstyanaxConfigurationImpl()      
     .setCqlVersion("3.0.0")) //using CQL3 

更新

查看 batch 关键字。批处理加速能力的主要因素是它节省了往返行程。管理 CQL 语句将更加困难,但它确实提高了更新速度。它可以执行 CUD 操作(插入、更新和删除),但不能执行 SELECT。另外我建议您通读CQL3 documentation 以了解 cql 可以做什么。

【讨论】:

  • 我刚试过 Astyanax 1.56.21,是的 asPreparedStatement() 丢失了。如果您使用 1.56.26,它将编译。
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 2013-01-12
  • 1970-01-01
  • 2015-09-12
  • 2013-04-04
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多