Batch Writes using Datastax Java driver?

23 views
Skip to first unread message

Check Peck

unread,
Aug 31, 2015, 5:22:43 PM8/31/15
to java-driver-user
I am using Datastax Java driver 2.1.7 and trying to use Batch Statement in an Atomic way. But the below code is not getting compile. I am seeing error on "batch.add" line as:-

    The method add(RegularStatement) in the type Batch is not applicable for the arguments (BoundStatement)
    
Below is the code:
    
    public void insertMetadata(List<DataMeta> metaAddress) {
        Batch batch = QueryBuilder.batch();
        try {
            for (DataMeta data : metaAddress) {
                PreparedStatement statement = session.prepare("INSERT INTO holder_table (address, name, last_modified_date, id) VALUES (?, ?, ?, ?)");
                batch.add(statement.bind(data.getAddress(), data.getName(), data.getLastModifiedDate(), 1));
            }
            batch.setConsistencyLevel(ConsistencyLevel.QUORUM);
            session.execute(batch);
        } catch (NoHostAvailableException e) {
            // log exception
        } catch (QueryExecutionException e) {
            // log exception
        } catch (QueryValidationException e) {
            // log exception
        }
    }

What is wrong?

Andrew Tolbert

unread,
Aug 31, 2015, 5:59:48 PM8/31/15
to DataStax Java Driver for Apache Cassandra User Mailing List
Hi Check,

The problem is that you are using Batch ('QueryBuilder.batch()') instead of BatchStatement ('new BatchStatement()').

Batch is meant to be used within the context of the QueryBuilder, and the 'add' method is intended to take Statements to append to a single query text using the 'BATCH' identifier.

Additionally a 'Batch' is executed as a 'QUERY' request using the 'BATCH' identifier which is considered a single statement, where 'BatchStatement' is executed as a 'BATCH' request which executes a series of statements populated via 'add'.

It's pretty confusing, but if you are using cassandra 2.0+, you should use BatchStatement.

Thanks,
Andy
Reply all
Reply to author
Forward
0 new messages