I need to write in Batches to Cassandra using Datastax Java driver and this is my first time I am trying to use batch with datastax java driver so I am having some confusion -
Below is my code in which I am trying to make a Statement object and adding it to Batch and setting the ConsistencyLevel as QUORUM as well.
Session session = null;
Cluster cluster = null;
// we build cluster and session object here and we use DowngradingConsistencyRetryPolicy as well
// cluster = builder.withSocketOptions(socketOpts).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)
public void insertMetadata(List<AddressMetadata> listAddress) {
// what is the purpose of unloggedBatch here?
Batch batch = QueryBuilder.unloggedBatch();
try {
for (AddressMetadata data : listAddress) {
Statement insert = insertInto("test_table").values(
new String[] { "address", "name", "last_modified_date", "client_id" },
new Object[] { data.getAddress(), data.getName(), data.getLastModifiedDate(), 1 });
// is this the right way to set consistency level for Batch?
insert.setConsistencyLevel(ConsistencyLevel.QUORUM);
batch.add(insert);
}
// now execute the batch
session.execute(batch);
} catch (NoHostAvailableException e) {
// log an exception
} catch (QueryExecutionException e) {
// log an exception
} catch (QueryValidationException e) {
// log an exception
} catch (IllegalStateException e) {
// log an exception
} catch (Exception e) {
// log an exception
}
}
And below is my AddressMetadata class -
public class AddressMetadata {
private String name;
private String address;
private Date lastModifiedDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
Now my question is - Does the way I am using Batch to insert into cassandra with Datastax Java Driver is correct? And what about retry policies, meaning if batch statement execution failed, then what will happen, will it retry again?
And is there any better way of using batch writes to cassandra using java driver?