5

Using cassandra object mapper api wanted to do a batch persist.

for single object it's working fine.

Mapper<MyObj> mapper = new MappingManager(getSession()).mapper(MyObj.class);
mapper.save(myObj);

For batch update I tried in this way, but ideally Cassandra is thinking I am persisting a list so it's giving exception like @Table annotation was not found in List, which is the expected behavior

Mapper<List<MyObj>> mapper = new MappingManager(getSession()).mapper(List.class);
myObjList.add(myObj1)
myObjList.addd(myObj2)
mapper.save(myObjList);

Is there a way to achieve the same in cassandra using batch?

NOTE: Alternatively I can do this by repeating the first step using for loop, but I am looking for a Batch insertions @ObjectMapper.

Community
  • 1
  • 1
lambodar
  • 3,495
  • 5
  • 34
  • 58

2 Answers2

11

Here is the snippet that I wanted to summarize form @adutra discussion in the above thread.

You can take the advantage of BatchStatement which is coming with cassandra-core driver and it's very much compatible with cassandra-mapper.

Mapper<MyObj> mapper = new MappingManager(getSession()).mapper(MyObj.class);
BatchStatement batch = new BatchStatement();
batch.add(mapper.saveQuery(myObj1));
batch.add(mapper.saveQuery(myObj2));
session.execute(batch);
lambodar
  • 3,495
  • 5
  • 34
  • 58
  • 3
    And to be really complete: the reason why I didn't direct you to the `BatchStatement` option initially is because batching queries is not necessarily the best option, sometimes executing each statement individually / in parallel can be much faster: see [this blog post](https://lostechies.com/ryansvihla/2014/08/28/cassandra-batch-loading-without-the-batch-keyword/) for more information. – adutra Mar 15 '16 at 09:24
3

There is no batch insertion utility in the Datastax object mapper framework.

You can either insert your entities one by one in a for loop, like you suggested, or look for a more advanced mapping framework, such as Achilles.

adutra
  • 4,231
  • 1
  • 20
  • 18
  • or you can use PreparedStatement like this topic suggests: http://stackoverflow.com/questions/19202812/how-to-use-asynchronous-batch-writes-feature-with-datastax-java-driver – nukie Mar 11 '16 at 15:12
  • @nukie you are right but I am looking for an Object-Mapper solutions. – lambodar Mar 14 '16 at 04:02
  • @adutra for a single/common feature of batch, It doesn't make sense of all together importing a library of achilles. If possible can you please add a backlog to support batch feature using object-mapper. – lambodar Mar 14 '16 at 04:09
  • 3
    Actually, this feature has already been requested, see [JAVA-706](https://datastax-oss.atlassian.net/browse/JAVA-706). You don't need anything special in the mapper to create a `BatchStatement` if that's what you want to do, see the comment in that ticket for an example. – adutra Mar 14 '16 at 12:03